如何在 Windows 上以编程方式捕获命令的输出
问题说了什么。
最终我想要的是执行 gcc 并 如果出现错误则捕获输出。问题是错误被写入 stderr 而不是 stdout。在 Linux 上我可以做
gcc foo.c 2>&1
如何在 Windows 上完成此操作?
What the question says.
Ultimately what I want is to execute gcc and capture the output if there's an error. The problem is errors are written to stderr instead of stdout. On Linux I can do
gcc foo.c 2>&1
How can I accomplish this on Windows?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有。只需右键单击控制台窗口,选择
标记
。用鼠标选择所需区域并右键单击。现在您可以使用 Ctrl-V 将其粘贴到文本文件中。如果您需要将程序的输出输出到文本文件中,请像这样运行它:
myprogram.exe > myfile.txt
请参阅此处有关重定向的信息:
1. 使用命令重定向运算符
2. 从命令提示符重定向错误消息:STDERR/STDOUT
你可以像这样做你想做的事:
D:\>dir 1>测试.txt 2> testerr.txt
There is. Simply right click into the console window, select
Mark
. With your mouse select the desired area and right click. Now you can paste it into a text file with Ctrl-V.If you need the output of a program into a text file, run it like this:
myprogram.exe > myfile.txt
See here about redirecting:
1. Using command redirection operators
2. Redirecting Error Messages from Command Prompt: STDERR/STDOUT
You can do what you want like this:
D:\>dir 1> test.txt 2> testerr.txt
理查德,你的“接受的答案”太长而且太错误了。
对您的问题的简短回答(如您最后一句话中所述:“我如何在 Windows 上完成此操作?”)是:
就像您在 Linux 上所做的一样!
但是我也会给你一个很长的答案。
您的
2>&1
重定向在cmd.exe
窗口中的工作方式相同。我现在甚至重新测试了它,因为我的 cmd.exe 体验有点生疏。我使用了这个 Ghostscript 命令(故意在 stdout 和 stderr 上生成输出):我将所有预期的输出都输入到了 shell 窗口中。然后我做了:
stderr 仍然打印到窗口中,但 stdout.log 具有“丢失”的原始输出。接下来我做了:
stdout 现在打印到窗口中,而 stderr.log 包含 Ghostscript 的其余消息。接下来:
并且(如预期):窗口中没有输出,所有输出在 stdout.log 和 stderr.log 之间分配。上次测试:
现在的结果:
这与 Linux 上的 stderr/stdout 重定向行为相同。
Richard, your "accepted answer" is too long and it is too wrong.
The short answer to your question (as currently stated in your last sentence: "How can I accomplish this on Windows?") is:
Exactly like you do it on Linux!
But I'll also give you a long answer.
Your
2>&1
redirection works in acmd.exe
window the same way. I even re-tested it right now, since my cmd.exe experience is a bit rusty. I used this Ghostscript command (intentionally meant to produce output on stdout as well as on stderr):I got all the expected output into the shell window. Then I did:
and stderr still printed into the window, but stdout.log had the 'missing' original output. Next I did:
and stdout now printed into window, while stderr.log had the rest of Ghostscript's messages. Next:
and (as expected): no output in window, all output divided up between stdout.log and stderr.log. Last test:
and result now:
Which is the same behaviour as stderr/stdout redirection as on Linux.
如果您想要特定命令的输出,有一种简单的方法可以将控制台输出推送到文件。
下面是一个使用“dir”命令的简单示例(前面的 > 代表您的提示符):
>dir > diroutput.txt
If you want the output of a particular command, there's a simple way to push console output to a file.
Here's a trivial example using the 'dir' command (the leading > represents your prompt):
>dir > diroutput.txt