我已經編寫了一個捕獲並執行命令行Python腳本的簡單程序,但有一個問題。傳遞給Python輸入函數的文本不會寫入我的程序,儘管我的程序捕獲了stdout。在標準輸出中沒有捕獲到某些Python命令
例如: 的Python腳本:
import sys
print("Hello, World!")
x = input("Please enter a number: ")
print(x)
print("This work?")
還會寫 「你好,世界!」然後停下來。當我通過一個數字時,它會繼續寫下「請輸入一個數字:3」。到底是怎麼回事?任何解決方案我的C#如下:
public partial class PyCon : Window
{
public string strPythonPath;
public string strFile;
public string strArguments;
private StreamWriter sw;
public PyCon(string pythonpath, string file, string args)
{
strPythonPath = pythonpath;
strFile = file;
strArguments = args;
InitializeComponent();
Process p = new Process();
p.StartInfo.FileName = strPythonPath;
p.StartInfo.Arguments = "\"" + strFile + "\" " + strArguments;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
sw = p.StandardInput;
}
private void p_OutputDataReceived(object sendingProcess, DataReceivedEventArgs received) {
if (!String.IsNullOrEmpty(received.Data)) {
AppendConsole(received.Data);
}
}
private void p_ErrorDataReceived(object sendingProcess, DataReceivedEventArgs received) {
if (!String.IsNullOrEmpty(received.Data)) {
AppendConsole(received.Data);
}
}
private void AppendConsole(string message) {
if (!txtConsole.Dispatcher.CheckAccess()) {
txtConsole.Dispatcher.Invoke(DispatcherPriority.Normal, (System.Windows.Forms.MethodInvoker)delegate() { txtConsole.AppendText(message + "\n"); });
} else {
//Format text
message = message.Replace("\n", Environment.NewLine);
txtConsole.AppendText(message + "\n");
}
}
private void txtInput_KeyUp(object sender, KeyEventArgs e) {
if (e.Key != Key.Enter) return;
sw.WriteLine(txtInput.Text);
txtInput.Text = "";
}
}
編輯:大量的研究後,並從該線程的幫助,我得出的結論是,問題是用Python的輸入命令不調用C#DataReceivedEventHandler。除了腳本更改外,可能還沒有解決方案。如果是這種情況,我會做出答案,包含所接受的更改。感謝您的幫助,夥計們!
該腳本的解決方法是偉大的。它糾正了這個問題,但並不理想。 設置PYTHONUNBUFFERED或使用-u運行腳本似乎無法解決問題。 – 2010-02-23 22:25:28