【发布时间】:2021-03-31 01:24:37
【问题描述】:
美好的一天! 有人建议我尝试一种方法,让 c# 运行 python 代码,然后将 python 输出发送到可以使用它的 c# 程序。
示例见链接:How do I run a Python script from C#?
我的实现:
private void run_cmd()
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "Path\\To\\python.exe";
start.Arguments = "Path\\To\\Thing.py";
;
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
if (result.Equals("-1.0"))
{
Print("Hello");
}
else if (result.Equals("1.0"))
{
Print("Hello");
}
process.WaitForExit();
//Print(result);
}
}
}
我实现了这个并且效果很好但是我没有将我的 python 程序的输出返回到 c# 程序中,c# 程序根本不会打印出“Hello”(打印命令对我所在的平台有效使用)。
以下是我尝试测试的打印语句。
print(1.0)
但没有给出输出。
任何帮助将不胜感激。
【问题讨论】:
-
我认为你的论点是错误的。
start.Arguments = string.Format("{0} {1}", "Path\\To\\Thing.py", start.FileName);应该是start.Arguments = "Path\\To\\Thing.py"。因为现在在shell中执行的命令是Path\\To\\python.exe Path\\To\\Thing.py Path\\To\\python.exe -
好的,我已经在我的程序上更改了它。所以我将以这种方式编辑问题。谢谢
-
在 python 输出中添加一个 '\0'。 ReadToEnd 无法识别 python 已完成并等待结束。
-
我尝试了这个并以下列方式编辑了我的 if 语句,if (result.Equals("1.0 \0") 但这不起作用。当 Python 打印时 ("1.0 \0")。
标签: python c# return connection ironpython