How do I run a Python script from C#?

后端 未结 8 1752
猫巷女王i
猫巷女王i 2020-11-22 02:47

This sort of question has been asked before in varying degrees, but I feel it has not been answered in a concise way and so I ask it again.

I want to run a script in

8条回答
  •  醉酒成梦
    2020-11-22 03:18

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

    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.

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

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

提交回复
热议问题