我正在尝试使用与“ cTrader”程序交互的API在C#脚本中运行一些Python代码,这就是所谓的“ cAlgo bot”。但是,我认为这部分与我遇到的问题在技术上不相关。我正在使用C#Python脚本运行器(下面的代码)运行Python代码。为此,我使用命令行,并使用空格分隔参数。
运行test_python_script1.py
时,输出成功打印在cTrader日志中,并且我在C#中访问该数据。但是,当我运行test_python_script2.py
时,输出不会通过。这些文件之间的唯一区别是第二个文件运行行model = torch.load("saved_model_1")
。我试图在此线路调用期间禁止控制台输出,但没有成功。
有人知道我如何运行此行并将输出输出到我的cAlgo机器人吗?
除了简单地使当前代码正常工作之外,还有三种潜在的解决方案:
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
}
}
}