首页 > 解决方案 > C# 中的 Python 嵌入(cTrader/cAlgo bot PyTorch 调用错误)

问题描述

我正在尝试在我的 C# 脚本中运行一些 Python 代码,该脚本称为“cAlgo bot”,使用与名为“cTrader”的程序交互的 API。但是,我认为这部分在技术上与我遇到的问题无关。我正在使用 C# Python 脚本运行器(下面的代码)运行 Python 代码。为此,我使用命令行,并给出用空格分隔参数的参数。

当我运行 test_python_script1.py时,输出成功打印在 cTrader 日志中,我在 C# 中访问该数据。但是,当我运行时test_python_script2.py,输出没有通过。这些文件之间的唯一区别是第二个文件运行该行 model = torch.load("saved_model_1")。我试图在此线路调用期间抑制控制台输出,但没有成功。

有谁知道我如何运行这条线并将输出输入到我的 cAlgo 机器人中?

除了简单地让当前代码工作之外,还有三个潜在的解决方案:

  1. 将 PyTorch 模型导出为 ONNX 模型,然后在 C# 中导入 ONNX 模型进行推理
  2. 使用 TorchSharp 直接将 PyTorch 模型导入 C#
  3. 尝试一种不同的 Python 到 C# 解释方法,称为“Python for .NET”

Python 脚本(“test_python_script1.py”)——(有效)

import sys import torch

# model = torch.load("saved_model_1")

def add_numbers(x,y):    sum = x + y    return sum

num1 = float(sys.argv[1]) num2 = float(sys.argv[2])

print(add_numbers(num1, num2))

Python 脚本(“test_python_script2.py”)——(不起作用)

import sys
import torch

model = torch.load("saved_model_1")

def add_numbers(x,y):
   sum = x + y
   return sum

num1 = float(sys.argv[1])
num2 = float(sys.argv[2])

print(add_numbers(num1, num2))

C# 脚本

using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class TomTest : Robot
    {
        // Windows username
        [Parameter(DefaultValue = "Tom")]
        public string WindowsUsername { get; set; }

        // Python script runner
        // args separated by spaces
        public static string RunFromCmd(string rWindowsUsername, string rCodeFilePath, string args)
        {
            string result = string.Empty;
            try
            {
                var info = new ProcessStartInfo("C:\\Users\\" + rWindowsUsername + "\\anaconda3\\python.exe")
                {
                    Arguments = rCodeFilePath + " " + args,

                    RedirectStandardInput = false,
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };
                using (var proc = new Process())
                {
                    proc.StartInfo = info;
                    proc.Start();
                    proc.WaitForExit();
                    if (proc.ExitCode == 0)
                    {
                        result = proc.StandardOutput.ReadToEnd();
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("Python script failed: " + result, ex);
            }
        }
        protected override void OnStart()
        {
            string test_python_script = TomTest.RunFromCmd(WindowsUsername, "C:\\Users\\" + WindowsUsername + "\\Desktop\\test_python_script.py", "0.5 0.5");
            Print("test script output: " + test_python_script);
        }
        protected override void OnTick()
        {
            // do nothing
        }
        protected override void OnStop()
        {
            // do nothing
        }
    }
}

标签: c#pythonalgorithmic-tradingpython-embedding

解决方案


推荐阅读