[英]Read from an external program/console
I have a problem, I need to execute a console program and I have to show the output information of that console on my program. 我有一个问题,我需要执行一个控制台程序,并且必须在程序上显示该控制台的输出信息。 I have a string variable called "result" that have to storage that information, but is always null and I don't know why. 我有一个名为“结果”的字符串变量,必须存储该信息,但始终为null,我不知道为什么。 Can anyone help me? 谁能帮我? I put the code below: 我把下面的代码:
Process p = new Process();
p.StartInfo.FileName = "python";
p.StartInfo.Arguments = @"C:\Users\xxx\xxx\xxx\xxx_\xxx yyy\zzz.py " + path;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
StreamReader sr = p.StandardOutput;
p.WaitForExit();
string result = sr.ReadToEnd();
sr.Close();
textBox1.Text = result;
On the console, I recieve 8382 JGK, for example, but my result variable is always "". 在控制台上,例如,我收到了8382 JGK,但是我的结果变量始终为“”。
You could try something like this 你可以尝试这样的事情
StreamReader sr = p.StandardOutput;
p.WaitForExit();
char[] result = new char[p.Length]; //or sr.BaseStream.Length
sr.Read(result,0,(int)p.Length); // again or sr.BaseStream.Length
And see if result array contains anything. 并查看结果数组是否包含任何内容。
I solve it! 我解决了! The problem was on the file's path. 问题出在文件的路径上。 I have to put it on the same folder as the ".py" file and it works fine. 我必须将其与“ .py”文件放在同一文件夹中,并且工作正常。 I add the correct piece of code: 我添加正确的代码:
string python = @"C:\xxx\python.exe";
string myPythonApp = "program.py";
string x = @"file.jpg";
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcessStartInfo.Arguments = myPythonApp + " " + x;
Process myProcess = new Process();
myProcess.StartInfo = myProcessStartInfo;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
StreamReader myStreamReader = myProcess.StandardOutput;
string myString = myStreamReader.ReadLine();
myProcess.WaitForExit();
myProcess.Close();
textBox1.Text = myString;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.