我正在编写一个C#程序来执行带有一些参数的python脚本。即使没有错误并且进程ExitCode为0(通过调试器检查),程序也不会执行(它不仅会打印出一条消息,而且还会写入文件)。我要去哪里错了?

    static private string ExecutePython(string sentence) {
        // full path of python interpreter
        string python = @"C:\Python27\python.exe";

        // python app to call
        string myPythonApp = @"C:\Users\user_name\Documents\pos_edit.py";

        // Create new process start info
        ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);

        // make sure we can read the output from stdout
        myProcessStartInfo.UseShellExecute = false;
        myProcessStartInfo.RedirectStandardOutput = true;


        myProcessStartInfo.Arguments = string.Format("{0} {1}", myPythonApp, sentence);

        Process myProcess = new Process();
        // assign start information to the process
        myProcess.StartInfo = myProcessStartInfo;

        // start process
        myProcess.Start();

        // Read the standard output of the app we called.
        StreamReader myStreamReader = myProcess.StandardOutput;
        string myString = myStreamReader.ReadToEnd();

        // wait exit signal from the app we called
        myProcess.WaitForExit();

        // close the process
        myProcess.Close();

        return myString;
}

最佳答案

您将myProcess.WaitForExit();放在错误的位置;等到Python执行了脚本:

...
myProcess.Start();

StreamReader myStreamReader = myProcess.StandardOutput;

// first, wait to complete
myProcess.WaitForExit();

// only then read the results (stdout)
string myString = myStreamReader.ReadToEnd();
...

10-08 09:02
查看更多