【问题标题】:Bash won't redirect output to a file and run in the background [duplicate]Bash不会将输出重定向到文件并在后台运行[重复]
【发布时间】:2020-05-13 20:54:28
【问题描述】:

我见过很多与此类似的问题,但问题是其他解决方案都没有解决我的问题。我想运行 2 个 python 脚本并使用 nohup 将它们的输出重定向到单独的日志文件。

此代码位于名为 startmain 的 bash 脚本中:

nohup python3 GUI.py > GUI.log 2>&1 &
nohup python3 main.py > main.log 2>&1 &

当我运行sh startmain 时,两个脚本都会执行,但没有任何内容写入任何一个日志文件。

现在假设我通过删除行尾的 & 字符来更改 startmain 代码:

nohup python3 GUI.py > GUI.log 2>&1
nohup python3 main.py > main.log 2>&1

这段代码说我不希望脚本在后台运行,所以只运行 GUI.py; 然而,它实际上将所有输出从 GUI.py 定向到 GUI.log。我知道为什么 main.py 不在这里运行,但我不知道为什么在这种情况下输出会写入 GUI.log,但当我尝试在后台运行脚本时却不知道。

知道我的问题是什么吗?我的问题与类似问题的不同之处在于我正在执行 2 个脚本,这可能是它不起作用的原因。

【问题讨论】:

  • nohup python3 -u GUI.py > GUI.log 2>&1 & 呢?
  • @KamilCuk 成功了!我在这里看到了 -u 选项的作用:reddit.com/r/learnpython/comments/5nvaic/… 但为什么解决了问题?
  • why did that fix the problem? 好吧,输出被缓冲在python 中,所以在写入指定的计数(如 4 KB)之前它不会输出。所以你“没有等待足够长的时间”。使用-u,它们是随用随写的。

标签: python bash stdout


【解决方案1】:

感谢@KamilCuk 的帮助!

添加-u 选项解决了这个问题:

nohup python3 -u GUI.py > GUI.log 2>&1
nohup python3 -u main.py > main.log 2>&1

但是为什么会这样呢?

因为默认情况下,stdout/stderr 输出是缓冲的,并且只在特定的时间间隔(例如每 1kB)被刷新。 “-u”选项使用python消除缓冲区,并将输出立即写入目标。

注意:这个问题实际上是nohup-is-not-writing-log-to-output-file的副本

【讨论】:

    猜你喜欢
    • 2015-09-29
    • 2021-11-04
    • 2018-11-07
    • 1970-01-01
    • 2011-10-04
    • 2020-05-10
    • 2020-08-03
    • 2019-10-11
    相关资源
    最近更新 更多