Python 脚本输出到控制台,即使它是这样的在后台运行
我正在后台运行 python 脚本,但为什么即使通过管道传输到文件,它仍然会打印到控制台?
我尝试了以下命令:
python script.py &
python script.py > output.txt &
我尝试使用一个简单的脚本:
print "hello world"
With
python script.py &
It 仍然打印到控制台。
但
python script.py > output.txt &
按预期工作并且不打印到控制台。
I am running a python script in background, but why does it still prints to console, even when piped to a file?
I tried the following command:
python script.py &
python script.py > output.txt &
I tried with a simple script:
print "hello world"
With
python script.py &
It still prints to console.
But
python script.py > output.txt &
works as intended and does not print to console.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
可能它正在 stderr 上输出。试试这个:
或者,您可能已经启动了一个仍在运行的后台任务:
输入
fg
将其带到前台,然后使用Ctrl-C
终止它。Probably it is outputing on stderr. Try this:
Alternatively it looks like you might have started a background task that is still running:
Type
fg
to bring it to the foreground, and then kill it withCtrl-C
.这里 python 的问题是它会缓冲 stdout 并且不会将其删除到磁盘。您需要像这样运行脚本
或者您可以使用无缓冲输出(程序内的 python 中的无缓冲标准输出(如 python -u))
The problem with python here is that it would buffer stdout and won't drop it to disk. You need to run your script like that
Or you can use unbuffered output (unbuffered stdout in python (as in python -u) from within the program)
有时甚至这还不够。某些应用程序写入 /dev/console 而不是 /dev/stdout 或 /dev/stderr。提示输入密码的应用程序通常会这样做。
Even this is not enough sometimes. Some applications write to /dev/console instead of /dev/stdout or /dev/stderr. Applications that prompt for a password often do this.
请参阅
此了解 < 用法的说明代码>2>&1
Should that have been
See this for a clarification on the usage of
2>&1
您打印到标准输出还是标准错误?这是两个不同的流。
Do you print to standard output or standard error? those are two different streams.