How do I run a Python script from C#?

后端 未结 8 1884
猫巷女王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:16

    I ran into the same problem and Master Morality's answer didn't do it for me. The following, which is based on the previous answer, worked:

    private void run_cmd(string cmd, string args)
    {
     ProcessStartInfo start = new ProcessStartInfo();
     start.FileName = cmd;//cmd is full path to python.exe
     start.Arguments = args;//args is path to .py file and any cmd line 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);
         }
     }
    }
    

    As an example, cmd would be @C:/Python26/python.exe and args would be C://Python26//test.py 100 if you wanted to execute test.py with cmd line argument 100. Note that the path the .py file does not have the @ symbol.

提交回复
热议问题