通过Tee将标准输出重定向到文件时,来自信号处理程序的日志隐藏

时间:2019-04-14 17:35:48

标签: python linux

我有一个像这样的python程序:

import signal, time

def cleanup(*_):
    print("cleanup")
    # do stuff ...
    exit(1)

# trap ctrl+c and hide the traceback message
signal.signal(signal.SIGINT, cleanup)

time.sleep(20)

我通过脚本运行程序:

#!/bin/bash

ARG1="$1"

trap cleanup INT TERM EXIT

cleanup() {
    echo "\ncleaning up..."
    killall -9 python >/dev/null 2>&1
    killall -9 python3 >/dev/null 2>&1
    # some more killing here ...
}

mystart() {
    echo "starting..."
    export PYTHONPATH=$(pwd)
    python3 -u myfolder/myfile.py $ARG1 2>&1 | tee "myfolder/log.txt"
}

mystart &&
cleanup

我的问题是 cleanup 消息没有出现在终端或日志文件上。

但是,如果我在不重定向输出的情况下调用程序,则效果很好。

3 个答案:

答案 0 :(得分:2)

按下^C会将SIGINT发送到整个foreground process group(当前管道或外壳“作业”),杀死tee才能将处理程序的输出写入任何地方。您可以在外壳中使用trap使针对SIGINT的命令免疫,尽管这样做存在明显的风险。

答案 1 :(得分:2)

如果您不希望发生这种情况,请将tee放在后台,这样它就不会成为获取SIGINT的流程组的一部分。例如,对于bash 4.1或更高版本,您可以使用自动分配的文件描述符(提供句柄)启动process substitution

#!/usr/bin/env bash
#              ^^^^ NOT /bin/sh; >(...) is a bashism, likewise automatic FD allocation.

exec {log_fd}> >(exec tee log.txt)  # run this first as a separate command
python3 -u myfile >&"$log_fd" 2>&1  # then here, ctrl+c will only impact Python...
exec {log_fd}>&-                    # here we close the file & thus the copy of tee.

当然,如果将这三个命令放在脚本中 ,则整个脚本将成为您的前台进程,因此需要使用不同的技术。因此:

python3 -u myfile > >(trap '' INT; exec tee log.txt) 2>&1

答案 2 :(得分:2)

只需使用-i的{​​{1}}或--ignore-interrupts选项。 文档说:

tee

https://helpmanual.io/man1/tee/