从C#调用python脚本不起作用,不会抛出错误

时间:2016-06-25 18:39:51

标签: c# python

我正在编写一个C#程序来执行带有一些参数的python脚本。程序没有被执行(它不仅应该打印出一条消息,而且还要写入一个文件),即使没有错误并且Process 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;
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

与我合作完美。我认为你的user_name包含空格。