2011-05-20 56 views
8

我正在學習C#的一些有趣的事情,我正在嘗試製作一個Windows應用程序,它有一些GUI用於運行一些Python命令。基本上,我試圖教導自己運行一個進程併發送命令給它,以及從它接收命令的膽量。Shellexecute = false爲什麼打破這個?

我此刻的下面的代碼:

Process p = new Process(); 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 
p.StartInfo.FileName = "C:/Python31/python.exe"; 
p.Start(); 
string output = p.StandardOutput.ReadToEnd(); 
p.WaitForExit(); 
textBox1.Text = output; 

從命令提示符下運行python.exe給出了一些,我想捕捉和發送到Windows窗體的文本框的介紹性文字(textBox1的)。基本上,目標是讓東西看起來像從Windows應用程序運行的Python控制檯。當我沒有將UseShellExecute設置爲false時,會彈出一個控制檯並且一切正常;但是,當我將UseShellExecute設置爲false以重新引導輸入時,我所得到的只是一個控制檯很快彈出並再次關閉。

我在這裏做錯了什麼?

回答

3

出於某種原因,你不應該使用斜線當你開始這個過程。

比較(不工作):

Process p = new Process(); 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 
p.StartInfo.RedirectStandardInput = true; 
p.StartInfo.CreateNoWindow = true; 

p.StartInfo.FileName = "C:/windows/system32/cmd.exe"; 
p.StartInfo.Arguments = "/c dir" ; 
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived); 
bool f = p.Start(); 
p.BeginOutputReadLine(); 
p.WaitForExit(); 


[...] 


static void p_OutputDataReceived(object sender, DataReceivedEventArgs e) 
{ 
    Console.WriteLine(e.Data); 
} 

到(按預期工作):

Process p = new Process(); 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 
p.StartInfo.RedirectStandardInput = true; 
p.StartInfo.CreateNoWindow = true; 

p.StartInfo.FileName = @"C:\windows\system32\cmd.exe"; 
p.StartInfo.Arguments = "/c dir" ; 
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived); 

bool f = p.Start(); 
p.BeginOutputReadLine(); 
p.WaitForExit(); 


[...] 

static void p_OutputDataReceived(object sender, DataReceivedEventArgs e) 
{ 
    Console.WriteLine(e.Data); 
} 
+0

謝謝!我現在可以使用這種方法運行python腳本(加上@Chris Haas提供的一些鏈接,但似乎不可能從交互式python exe得到完整的輸出 – 2011-05-20 13:52:11

+0

當您不使用ShellExecute ,所調用的API是'CreateProcess',並且已知不接受'/'作爲目錄分隔符。 – 2011-05-20 16:06:45

1

Python似乎在做一些奇怪的事情。直到我測試它然後做了一些研究,我纔會相信它。但是,所有這些崗位基本上似乎有完全相同的問題:

+1

請問,如果你從正變爲反斜槓它仍然無法正常工作?它使我的測試與cmd有所不同,但我沒有安裝python,所以我無法用python進行測試... – 2011-05-20 13:28:48

+0

感謝你們的回覆 - 我用反斜槓測試了代碼,它仍然彈出控制檯窗口,然後很快消失。這確實很奇怪! – 2011-05-20 13:46:52

+1

我用Python 2.6對它進行了測試,但無法使其正常工作。我使用了正斜槓,除了StdOut之外還檢查了StdErr,設置了環境變量'PYTHONUNBUFFERED',傳遞了'-v​​'作爲參數,甚至使用了異步數據接收處理程序,並且無法使其工作。 – 2011-05-20 13:54:27