【发布时间】:2020-07-31 08:25:11
【问题描述】:
我想在 C# 中运行一个 python 脚本,然后想将 python 脚本的“返回值”返回到 C#。
我的python脚本:
def myfunc():
print("aaa")
return "abc"
if __name__ == "__main__":
myfunc()
我的 C# 文件:
void Main()
{
var result = run_cmd();
Console.WriteLine(result);
}
private string run_cmd()
{
string fileName = @"C:\Users\NCH-Lap10\Desktop\return_one.py";
string python = @"C:\Users\NCH-Lap10\AppData\Local\Programs\Python\Python37-32\python.exe";
Process psi = new Process();
psi.StartInfo = new ProcessStartInfo(python, fileName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = false
};
psi.Start();
string output = psi.StandardOutput.ReadToEnd();
Console.WriteLine(output);
psi.WaitForExit();
int result = psi.ExitCode;
return output;
}
我可以返回打印的消息“aaa”,但我需要“abc”。我认为 psi.ExitCode 会给我所需的输出,但它不起作用。
【问题讨论】:
-
我认为,您需要一个嵌入式 Python 解释器。如果您的数据简单且可序列化,请考虑使用套接字传递数据。
标签: python c# return-value processstartinfo