【问题标题】:Python subprocess.call() add prefix to each stdout and stderr linePython subprocess.call() 为每个 stdout 和 stderr 行添加前缀
【发布时间】:2012-12-05 18:42:49
【问题描述】:

我正在使用 python 来运行一些 shell 脚本、RScripts、python 程序等。这些程序可能会运行很长时间,并且可能会向 stdout 和 stderr 输出大量(日志记录)信息。我正在使用以下(Python 2.6)代码,它工作正常:

stdoutFile=open('stdout.txt', 'a')
stderrFile=open('stderr.txt', 'a')
subprocess.call(SHELL_COMMAND, shell=True, stdout=stdoutFile, stderr=stderrFile)
stdoutFile.close()
stderrFile.close()

这主要是记录到文件中的信息,这些信息可以在很长一段时间内生成。因此我想知道是否可以在每一行前面加上日期和时间?

例如,如果我当前要登录:

Started
Part A done
Part B done
Finished

那么我希望它是:

[2012-12-18 10:44:23] Started
[2012-12-18 12:26:23] Part A done
[2012-12-18 14:01:56] Part B done
[2012-12-18 22:59:01] Finished

注意:修改我运行的程序不是和选项,因为这个 python 代码有点像这些程序的包装器。

【问题讨论】:

    标签: python datetime logging subprocess stdout


    【解决方案1】:

    不要将文件提供给subprocess.call() 的stdout 和stderr 参数,而是直接创建一个Popen 对象并创建PIPEs,然后在此管理器脚本中读取这些管道并预先添加任何标签在写入您想要的任何日志文件之前想要。

    def flush_streams_to_logs(proc, stdout_log, stderr_log):
        pipe_data = proc.communicate()
        for data, log in zip(pipe_data, (stdout_log, stderr_log)):
            # Add whatever extra text you want on each logged message here
            log.write(str(data) + '\n')
    
    with open('stdout.txt', 'a') as stdout_log, open('stderr.txt', 'a') as stderr_log:
        proc = subprocess.Popen(SHELL_COMMAND, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        while proc.returncode is None:
            flush_streams_to_logs(proc, stdout_log, stderr_log)
        flush_streams_to_logs(proc, stdout_log, stderr_log)
    

    注意communicate() 会阻塞直到子进程退出。您可能希望直接使用子进程的流,以便获得更多实时日志记录,但您必须自己处理并发和缓冲区填充状态。

    【讨论】:

    • 我认为第二个选项不起作用,因为它们缺少用于(直接)写入的 .fileno() 方法。尽管如此,第一个 +1。
    • 啊,有趣,看起来你是对的。我将删除第二个位。
    猜你喜欢
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多