为什么Shellexecute = false打破这个?

时间:2011-05-20 12:54:15

标签: c# winforms

我现在正在学习C#以获得一些乐趣,并且我正在尝试制作一个具有运行某些python命令的gui的Windows应用程序。基本上,我正在努力教会自己运行进程并向其发送命令的勇气,以及从中接收命令。

目前我有以下代码:

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以重新定向输入时,我得到的是控制台快速弹出并再次关闭。

我在这里做错了什么?

2 个答案:

答案 0 :(得分: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);
}

to(按预期工作):

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);
}

答案 1 :(得分:1)

Python似乎在做一些奇怪的事情。直到我测试它然后做了一些研究,我才会相信它。但所有这些帖子似乎都有同样的问题:

相关问题