如何从C#运行Python脚本?
之前曾在不同程度上提出过这样的问题,但我觉得并没有以简洁的方式回答过,因此我再次提出。
我想在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);
}
}
}
当我传递code.py
位置as cmd
和filename
位置as
args
无效时。有人告诉我,我应该通过python.exe
的cmd
,然后code.py filename
作为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);
}
}
回答:
它不起作用的原因是因为您有UseShellExecute = false
。
如果不使用外壳程序,则必须以方式提供python可执行文件的完整路径FileName
,并构建Arguments
字符串以提供脚本和要读取的文件。
另请注意,RedirectStandardOutput
除非您不能这样做UseShellExecute = false
。
我不太确定应如何为python格式化参数字符串,但您将需要以下内容:
private void run_cmd(string cmd, string args){
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "my/full/path/to/python.exe";
start.Arguments = string.Format("{0} {1}", cmd, 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);
}
}
}
以上是 如何从C#运行Python脚本? 的全部内容, 来源链接: utcz.com/qa/422507.html