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;
}
3
  • Does your "user_name" contain any spaces? Commented Jun 25, 2016 at 18:43
  • Possible duplicate of run a python script from c# Commented Jun 25, 2016 at 18:46
  • @Aya no. But I got an alternative to work without taking stdout. Commented Jun 26, 2016 at 8:38

2 Answers 2

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();
...
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.