goluhaque
goluhaque

Reputation: 571

Calling python script from C# doesn't work, without throwing error

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

Upvotes: 1

Views: 1196

Answers (2)

Ryan B.
Ryan B.

Reputation: 1402

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

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

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();
...

Upvotes: 1

Related Questions