这种问题以前也有不同程度的问过,但感觉没有得到简洁的回答,所以再问一次。
我想在 Python 中运行脚本。假设是这样的:
if __name__ == '__main__':
with open(sys.argv[1], 'r') as f:
s = f.read()
print s
它获取文件位置,读取它,然后打印其内容。没那么复杂。
好的,那么我如何在 C# 中运行它呢?
这就是我现在所拥有的:
private void run_cmd(string cmd, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = cmd;
start.Arguments = args;
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
当我通过 filename
code.py
位置为 cmd
args
I was told I should pass python.exe
as the cmd
, and then code.py filename
as the args
.
我已经找了一段时间了,只能找到建议使用 IronPython 之类的人。但是必须有一种方法可以从 C# 调用 Python 脚本。
一些说明:
我需要从 C# 运行它,我需要捕获输出,我不能使用 IronPython 或其他任何东西。无论你有什么技巧都可以。
PS:我运行的实际 Python 代码比这复杂得多,它返回我在 C# 中需要的输出,C# 代码将不断调用 Python 代码。
假装这是我的代码:
private void get_vals()
{
for (int i = 0; i < 100; i++)
{
run_cmd("code.py", i);
}
}
原文由 Inbar Rose 发布,翻译遵循 CC BY-SA 4.0 许可协议
它不起作用的原因是因为您有
UseShellExecute = false
。如果不使用 shell,则必须提供 python 可执行文件的完整路径
FileName
,并构建Arguments
字符串以提供脚本和文件想读。另请注意,您不能
RedirectStandardOutput
除非UseShellExecute = false
。我不太确定应该如何为 python 设置参数字符串的格式,但你需要这样的东西: