【问题标题】:Bash redirection in a script in parallel并行脚本中的 Bash 重定向
【发布时间】:2017-02-14 11:37:40
【问题描述】:

我有一个 bash 脚本,其中包含我想要并行运行的进程循环:

for i in {1..5}
do
echo Running for simulation $i
python script.py $i > ./outlogs/$i.log 2>&1 &
done

但是当我这样做时,文件重定向不起作用,所以$i.log 只是保持为空。重定向仅在我最后不使用 & 时才有效,但是脚本会等待每个进程完成,然后再开始下一个进程,这是我不想要的。

我尝试了使用script -c 的解决方案,但这不会实时更新,只有在流程结束后才会更新。有没有人有更好的建议,文件重定向在这个脚本中起作用但它仍然实时更新?

【问题讨论】:

  • 重定向到底是什么意思?你启动 5 个进程,每个进程都有 std(in|out|err)
  • 是的,就像将每个子进程的stdout和stderr重定向到文件./outlogs/$i.log
  • 你的脚本看起来不错,我的意思是每个子进程的 stdout 和 strerr 都转到不同的文件,1 到 1.log,2 到 2.log 等。
  • 我的意思是我把你的 python 脚本改成了非常简单的脚本,比如 #!/bin/bash echo "to error" 1>&2;睡眠 5 回声 $*;它工作正常
  • 啊好吧,看起来问题出在 python 的缓冲而不是 bash 本身!

标签: linux bash redirect stdout


【解决方案1】:

您只需添加-u 选项,它会如下所示:

python -u script.py $i > ./outlogs/$i.log 2>&1 &

选项-u 用于无缓冲的二进制标准输出和标准错误

【讨论】:

    猜你喜欢
    • 2014-11-17
    • 1970-01-01
    • 2010-10-01
    • 2020-03-22
    • 2012-05-30
    • 2013-08-08
    • 2011-05-19
    • 2015-09-15
    • 1970-01-01
    相关资源
    最近更新 更多