我现在正在学习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以重新定向输入时,我得到的是控制台快速弹出并再次关闭。
我在这里做错了什么?
答案 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)