Python 脚本输出到控制台,即使它是这样的在后台运行

发布于 2024-08-20 06:11:53 字数 410 浏览 8 评论 0原文

我正在后台运行 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

-柠檬树下少年和吉他 2024-08-27 06:11:53

可能它正在 stderr 上输出。试试这个:

python script.py > output.txt 2>&1 &

或者,您可能已经启动了一个仍在运行的后台任务:

python script.py &

输入 fg 将其带到前台,然后使用 Ctrl-C 终止它。

Probably it is outputing on stderr. Try this:

python script.py > output.txt 2>&1 &

Alternatively it looks like you might have started a background task that is still running:

python script.py &

Type fg to bring it to the foreground, and then kill it with Ctrl-C.

水中月 2024-08-27 06:11:53

这里 python 的问题是它会缓冲 stdout 并且不会将其删除到磁盘。您需要像这样运行脚本

python -u script.py > output.txt &

或者您可以使用无缓冲输出(程序内的 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

python -u script.py > output.txt &

Or you can use unbuffered output (unbuffered stdout in python (as in python -u) from within the program)

破晓 2024-08-27 06:11:53

有时甚至这还不够。某些应用程序写入 /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.

隐诗 2024-08-27 06:11:53

请参阅

python script.py > output.txt 2>&1 & 
python script.py >> output.txt 2>&1 

了解 < 用法的说明代码>2>&1

Should that have been

python script.py > output.txt 2>&1 & 
python script.py >> output.txt 2>&1 

See this for a clarification on the usage of 2>&1

回首观望 2024-08-27 06:11:53

您打印到标准输出还是标准错误?这是两个不同的流。

Program 2> file # pipe standard error
Program 2>&1 # pipe standard error to standard output (join streams)
Program > file 2>&1 # pipe both channels to file

Do you print to standard output or standard error? those are two different streams.

Program 2> file # pipe standard error
Program 2>&1 # pipe standard error to standard output (join streams)
Program > file 2>&1 # pipe both channels to file
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文