这类问题以前也曾在不同程度上提出过,但我觉得没有得到简明的答覆,所以我再提出一次。
我想用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位置作为cmd传递,并将filename位置作为args传递时,它无法工作。我被告知应该将python.exe作为cmd传递,然后将code.py filename作为args传递。
我现在已经找了一段时间了,只能找到建议使用IronPython之类的人。但是必须有一种从C#调用Python脚本的方法。
一些澄清:
我需要从C#运行它,我需要捕获输出,而且我不能使用IronPython或其他任何东西。不管你有什么手段都可以。
注:我正在运行的实际Python代码比这个复杂得多,它返回的是我在C#中需要的输出,而C#代码将不断地调用Python代码。
假装这是我的代码:private void get_vals()
{
for (int i = 0; i < 100; i++)
{
run_cmd("code.py", i);
}
}