首页 > 解决方案 > 将 nohup 重定向到脚本上的标准输出

问题描述

我有一个.sh通过nohup运行大量 Python 脚本的脚本。

我习惯nohup在后台运行它们,并避免在出现“ nohup:忽略输入并将输出附加到'nohup.out' ”消息时进行必要的输入。

nohup python script2.py 2> /dev/null &
nohup python script2.py 2> /dev/null &
[...]

当我运行这个.sh时,我得到两个 Python 脚本在后台运行,好的。

这个 Python 脚本生成一个日志文件,我将其派生到std.stdout

stream_config = logging.StreamHandler(sys.stdout)  <-- here
stream_config.setFormatter(formatter)
importer_logger.addHandler(stream_config)  

由于我的实施,我想启动那些nohup但将标准输出发送到 PID 1

我可以很容易地做到这一点,而无需使用nohup如下:

python tester.py > /proc/1/fd/1

但是我怎样才能将“不要按回车继续”和“将文件导出到标准输出”结合起来呢?

我没有运气尝试了这些:

nohup python tester.py > /proc/1/fd/1 2> /dev/null &
nohup python tester.py 2> /proc/1/fd/1 &

提前致谢。

标签: pythonlinuxunixnohup

解决方案


您可以通过使用 shell 间接启动您的程序来修复您的命令,以便您可以重定向其输出而不是 nohup 的输出:

nohup bash -c "exec python tester.py > /proc/1/fd/1" 2> /dev/null &

这不是最佳选择,但它至少纠正了导致您的尝试失败的问题。


推荐阅读