这类问题以前有不同程度的被问过,但我觉得没有得到简明的回答,所以我又问了一遍。
我想用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);
}
}
它不起作用的原因是您有
UseShellExecute = false
。如果不使用shell,则必须以
FileName
的形式提供python可执行文件的完整路径,并构建Arguments
字符串以同时提供脚本和要读取的文件。还要注意,除非
UseShellExecute = false
,否则不能RedirectStandardOutput
。我不太确定python的参数字符串应该如何格式化,但您需要这样的东西:
从C
执行Python脚本创建一个C#项目并编写以下代码。
Python示例脚本
您将在C的控制台中看到“Python C#Test”。
如果您愿意使用IronPython,可以直接在C#:
Get IronPython here.
相关问题 更多 >
编程相关推荐