1

我正在尝试构建一个 .net 应用程序,它将运行一些控制台命令(如运行 phantomJs)并返回操作结果。但默认情况下,我会得到从开始cmd.exe到关闭的所有内容。有什么快速修复的想法还是我需要使用正则表达式?

这是我现在的代码:

System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardError = true;

System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
System.IO.StreamReader sOut = proc.StandardOutput;

System.IO.StreamWriter sIn = proc.StandardInput;

sIn.WriteLine("phantomjs -v");
sIn.WriteLine("EXIT");

proc.Close();

string results = sOut.ReadToEnd().Trim();

sIn.Close();
sOut.Close();
4

4 回答 4

2

PhantomJS 是一个可执行文件(根据他们的文档) - 为什么不直接执行它而不是运行 cmd.exe?这将避免 cmd.exe 噪音。

或者将phantomjs的输出重定向到一个日志文件并加载日志文件。

或者,如果您绝对必须使用 cmd.exe 并且无法重定向......我可能会在 phantomjs 周围抛出一些回声哨兵作为解析开始/停止点。

例如,

echo PARSE START
runcommand.exe
echo PARSE STOP

但不要那样做。

于 2012-12-27T12:59:32.433 回答
1

而不是使用不同的流。为什么不使用cmdasfilename并将其传递给-c "phantomjs -v"as 参数。然后用于proc.StandardOutput.ReadToEnd()抓取控制台中输出的所有内容。这应该忽略不需要的信息,因为它只读取执行命令的输出。

下面的代码可能不起作用,但应该给你一个大致的想法。

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "cmd";
psi.Arguments = "/c \"phantomjs -v\"";
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
// Optional other options

Process proc = Process.Start(psi);

string output = proc.StandardOutput.ReadToEnd();

proc.WaitForExit();
于 2012-12-27T13:01:21.057 回答
0

如果您在 unix 机器上:

sIn.WriteLine("phantomjs -v > /dev/null");

视窗:

sIn.WriteLine("phantomjs -v > NUL");
于 2012-12-27T12:56:47.153 回答
0

我希望以下内容会有所帮助!

{

 Process xyProcess = new Process();

 xyProcess.StartInfo.FileName = "FilenameYouWant";
 xyProcess.StartInfo.UseShellExecute = false;
 xyProcess.StartInfo.CreateNoWindow = true;
 xyProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
 xyProcess.StartInfo.RedirectStandardInput = true;
 xyProcess.StartInfo.RedirectStandardOutput = true;
 xyProcess.StartInfo.RedirectStandardError = true;

 xyProcess.StartInfo.Arguments += "any arg1 you want ";
 xyProcess.StartInfo.Arguments += "any arg2 you want ";

 xyProcess.EnableRaisingEvents = true;
 xyProcess.OutputDataReceived += process_DataReceived;

 // Start the process
 xyProcess.Start();
 xyProcess.BeginErrorReadLine();
 xyProcess.BeginOutputReadLine();
 xyProcess.WaitForExit();

}
static private void process_DataReceived(object sender, DataReceivedEventArgs e)
{
    //Catch the process response here
}
于 2012-12-27T13:42:38.333 回答