1

I am writing a C# program to execute a python script with some arguments. The program is not executed(it is supposed to not only print out a message, but also to write to a file), even though there is no error and the Process ExitCode is 0(checked via the debugger). Where am I going wrong?

    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;
}
goluhaque
  • 561
  • 5
  • 17

2 Answers2

1

You've put myProcess.WaitForExit(); in the wrong place; wait till Python has executed the script:

...
myProcess.Start();

StreamReader myStreamReader = myProcess.StandardOutput;

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

// only then read the results (stdout)
string myString = myStreamReader.ReadToEnd();
...
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Works perfectly fine with me. I think there's something with your user_name containing spaces.

Ryan B.
  • 1,270
  • 10
  • 24