【问题标题】:Bash - redirect stdout and stderr to files with background processBash - 将标准输出和标准错误重定向到具有后台进程的文件
【发布时间】:2015-09-16 21:23:49
【问题描述】:

我为我正在构建的应用程序创建了一个简单的初始化脚本。脚本的开始部分如下所示:

user="ec2-user"

name=`basename $0`
pid_file="/var/run/python_worker.pid"
stdout_log="/var/log/worker/worker.log"
stderr_log="/var/log/worker/worker.err"

get_pid() {
    cat "$pid_file"
}

is_running() {
    [ -f "$pid_file" ] && ps `get_pid` > /dev/null 2>&1
}

case "$1" in
    start)
    if is_running; then
        echo "Already started"
    else
        echo "Starting $name"
        cd /var/lib/worker
        . venv/bin/activate
        . /etc/profile.d/worker.sh
        python run.py  >> "$stdout_log" 2>> "$stderr_log" &
        echo $! > "$pid_file" 
        if ! is_running; then
            echo "Unable to start, see $stdout_log and $stderr_log"
            exit 1
        fi
        echo "$name running"
    fi

我遇到了这条线的问题:

python run.py  >> "$stdout_log" 2>> "$stderr_log" &

我想用这段代码启动我的应用程序并将输出重定向到上面指定的文件。但是,当我包含 & 以使其在后台运行时,两个日志文件中没有出现任何内容。但是,当我从这一行中删除 & 时,日志文件会获取数据。为什么会这样?

显然我需要运行命令以使其作为后台进程运行,以停止 shell 等待。

我还确定当我使用 & 时进程正在运行。我可以通过ps -aux 找到它:

root     11357  7.0  3.1 474832 31828 pts/1    Sl   21:22   0:00 python run.py

有人知道我做错了什么吗? :)

【问题讨论】:

    标签: python linux bash init


    【解决方案1】:

    有人知道我做错了什么吗? :)

    简答:

    是的。将-u 添加到 python 命令中,它应该可以工作。

    python -u run.py  >> "$stdout_log" 2>> "$stderr_log" &
    

    长答案:

    这是一个缓冲问题(来自man python):

       -u     Force stdin, stdout and stderr to be totally unbuffered.  On systems where it matters, also put stdin, stdout
              and  stderr  in  binary  mode.   Note that there is internal buffering in xreadlines(), readlines() and file-
              object iterators ("for line in sys.stdin") which is not influenced by this option.  To work around this,  you
              will want to use "sys.stdin.readline()" inside a "while 1:" loop.
    

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 1970-01-01
      • 2022-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-12
      相关资源
      最近更新 更多