Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在后台运行程序,并将其输出实时重定向到文件_Python_Bash_Redirect_Background Process - Fatal编程技术网

Python 在后台运行程序,并将其输出实时重定向到文件

Python 在后台运行程序,并将其输出实时重定向到文件,python,bash,redirect,background-process,Python,Bash,Redirect,Background Process,我想在一个bash会话中同时运行几个python脚本,并分别实时检查它们的输出。为了完成这项任务,我编写了一个简单的bash脚本,如下所示: #!/bin/bash python 1.py > 1.output & python 2.py > 2.output & python 3.py > 3.output & 当我使用 CAT 1。输出< /Cord>命令检查在执行过程中打印的内容,但是,什么也看不到。 思考了一会儿之后,我意识到当1.py完成执行

我想在一个bash会话中同时运行几个python脚本,并分别实时检查它们的输出。为了完成这项任务,我编写了一个简单的bash脚本,如下所示:

#!/bin/bash
python 1.py > 1.output &
python 2.py > 2.output &
python 3.py > 3.output &

当我使用<代码> CAT 1。输出< /Cord>命令检查在执行过程中打印的内容,但是,什么也看不到。 思考了一会儿之后,我意识到当

1.py
完成执行时,必须填充
1.output
。换句话说,我在这里使用的方法不是一种
实时
方式

您可以建议等待这些python脚本的完成。不幸的是,所有这些python脚本实际上都是长时间运行的程序,它们可能在几天或几个月后完成,这就是为什么我想实时检查它们的输出

另外,您可能建议我修改python脚本,将消息直接打印到文件中,而不是
stdout
。抱歉,这里的脚本太复杂,无法修改,其中包含
打印功能的卡盘


我现在能做什么呢?

如果你能在程序中找到某种主循环,这可能是一个很好的进度指示器,那么最好写文件。如果您说输出流在Python关闭之前不会填充,那么这可能是最简单的选择。

您可以尝试通过以下操作在脚本中重写stderr/stdout:

# in the beginning of your script
import os
import sys

desired_output_file = open('/path/to/file', 'a')
os.dup2(desired_output_file.fileno(), sys.stdout)
os.dup2(desired_output_file.fileno(), sys.stderr)

然后所有的
print
调用都会写入这个特殊文件,而不是stdout。然而,主要问题可能是缓冲IO。您必须以某种方式
将此类文件的内容刷新到磁盘。

-u
开关和等效的
PYTHONUNBUFFERED
环境变量强制取消缓冲stdout。试试这个:

#!/bin/bash
python -u 1.py > 1.output &
python -u 2.py > 2.output &
python -u 3.py > 3.output &

注意
-u
有副作用:阅读文档了解更多信息

参考:


让python脚本定期刷新其输出…请发布用于此日志记录操作的代码。
#!/bin/bash
export PYTHONUNBUFFERED=yes
python 1.py > 1.output &
python 2.py > 2.output &
python 3.py > 3.output &