gpt4 book ai didi

c# - process.Start() 在 C# 中无法调用 python 脚本

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:14 24 4
gpt4 key购买 nike

抱歉,如果这是显而易见的事情,我是 C# 的 super 新手。我正在开发一个运行 python 脚本以在线检查某些内容的程序,然后将其写回 C# 读取并放入表单的文件。如果我同时手动运行它们,一切都会正常,但我真的想从 C# 程序启动脚本。

这是应该启动 python 脚本的函数:

private void RunPython()
{
Process p = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "python " + path + "\\foo.py";
p.StartInfo = startInfo;
p.Start();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
// get things set up... etc.
RunPython();
}

我试过在没有隐藏窗口的情况下运行它,它只会在“路径”目录中显示一个空的 cmd 行。它从不运行 python 脚本吗?它看起来不像,但它也可能正在运行它并立即关闭它。我不知道。

我需要它在 C# 程序运行期间保持打开状态,所以如果问题是它在 RunPython() 方法返回时退出,是否有一些不同的方法可以解决这个问题?

谢谢!!

最佳答案

如果您想使用 cmd.exe 的参数在命令行中运行程序,您需要 /c 标志。或者,您可以使用 /k,但这会使命令进程保持运行,而您可能不希望这样做。

/c Carries out the command specified by String and then stops.

所以它的用法是cmd.exe/c [string]

尝试将您的参数行更改为:

startInfo.Arguments = "/c \"python " + path + "\\foo.py\"";

有关运行 cmd.exe 和处理命令的 string 部分中的引号的更多信息,请参见此处:https://technet.microsoft.com/en-us/library/cc771320(v=ws.11).aspx

关于c# - process.Start() 在 C# 中无法调用 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44294314/

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