gpt4 book ai didi

c# - 如何从 C# 运行 Python 脚本?

转载 作者:IT老高 更新时间:2023-10-28 21:06:17 24 4
gpt4 key购买 nike

这种问题以前也有不同程度的问过,但感觉回答得不够简洁,所以又问了一遍。

我想在 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 文件名 作为 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);
}
}

最佳答案

它不工作的原因是因为你有 UseShellExecute = false

如果您不使用 shell,则必须将 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# - 如何从 C# 运行 Python 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11779143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com