【发布时间】:2017-05-18 07:21:39
【问题描述】:
这样的问题以前也有不同程度的问过,但是感觉回答的不够简洁,所以又问了一遍。
我想在 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 或其他任何东西。无论你有什么技巧都可以。
P.S.:我实际运行的 Python 代码比这复杂得多,它会返回我在 C# 中需要的输出,而 C# 代码会不断调用 Python 代码。
假装这是我的代码:
private void get_vals()
{
for (int i = 0; i < 100; i++)
{
run_cmd("code.py", i);
}
}
【问题讨论】:
-
C# 代码是否必须调用 Python 脚本,或者如果(如您最后所说)您只需调用然后运行脚本的 python 解释器就可以了吗?
-
你可以使用 IronPython 吗?
-
@GeraldVersluis 没关系,我只需要能够通过 c# 运行它并捕获输出。
标签: c# python .net ironpython python.net