2016-06-25 32 views
1

我在寫一個C#程序來執行一些帶有參數的python腳本。即使沒有錯誤並且Process ExitCode爲0(通過調試器檢查),程序也不會執行(它不僅應該打印出消息,而且還要寫入文件)。我哪裏錯了?從C#調用python腳本不起作用,沒有拋出錯誤

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

您的「user_name」是否包含空格? – Aya

+0

[從c#運行python腳本]的可能重複(http://stackoverflow.com/questions/11779143/run-a-python-script-from-c-sharp) – Mate

+0

@Aya no。但是我有一個替代方案,不用輸入stdout。 – goluhaque

回答

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

完美的作品我沒問題。我認爲你的user_name包含空格。

相關問題