且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 C# 运行 Python 脚本?

更新时间:2023-02-12 13:32:03

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

The reason it isn't working is because you have UseShellExecute = false.

如果您不使用 shell,则必须提供 python 可执行文件的完整路径作为 FileName,并构建 Arguments 字符串以提供您的脚本和您要读取的文件.

If you don't use the shell, you will have to supply the complete path to the python executable as FileName, and build the Arguments string to supply both your script and the file you want to read.

另请注意,除非UseShellExecute = false,否则您不能RedirectStandardOutput.

Also note, that you can't RedirectStandardOutput unless UseShellExecute = false.

我不太确定应该如何为 python 设置参数字符串的格式,但您需要这样的东西:

I'm not quite sure how the argument string should be formatted for python, but you will need something like this:

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);
         }
     }
}