【问题标题】:Python - How to write in both files and console at the same time (from a Bash files)Python - 如何同时写入文件和控制台(来自 Bash 文件)
【发布时间】:2017-10-19 13:53:34
【问题描述】:
with open('WarningErr.txt', 'w') as err:
    subprocess.call(cmd, stderr=err)

with open('WarningOut.txt', 'w') as out:
    return_code = subprocess.call(cmd, stdout=out)

现在,我将错误和输出都写在“.txt 和 stdout”中。

但是太慢了。我写在一个,然后在另一个。 我必须能够同时写两者。

复制一点 Bash 中的 tee 行为。

【问题讨论】:

标签: python subprocess stdout


【解决方案1】:

猜你喜欢登录到 stdout/stderr 和一个文件。试试日志库和这段代码:

import logging

# create logger obj
_glogger = logging.getLogger("myApp")

# create file sink
hdlr = logging.FileHandler(os.path.join("dumpDir",'myApp.log'))
formatter = logging.Formatter('%(asctime)s %(name)s[%(process)d] %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
_glogger.addHandler(hdlr)

# create steam sink = stdout
hdlr2 = logging.StreamHandler()
hdlr2.setFormatter(formatter)
_glogger.addHandler(hdlr2)
_glogger.setLevel(logging.DEBUG)

_glogger.debug("a debug message")

【讨论】:

  • 是的,这是我最终必须尝试的。
【解决方案2】:

我像@Rightleg 建议的那样在命令调用中包含了 tee。我改变命令。但现在它完美地工作了。

我不认为我可以通过子进程调用 tee。但是效果真的很好!

 # for example
 command = 'ls'

 # To write at the same time in the shell and a file both errors, and stdout (TEE behaviour)
 cmd = ['bash', '-c', '. myBash.bash; {} > >(tee {}/WarningOut.txt) 2> >(tee {}/WarningErr.txt >&2)'
       .format(command, PATHTOWHEREYOUWANTIT_g, PATHTOWHEREYOUWANTIT_g)]

return_code = subprocess.call(cmd)

【讨论】:

  • 能否请您添加您的最终代码,以便对其他用户有所帮助? :)
猜你喜欢
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-14
  • 2013-02-05
  • 2017-09-30
相关资源
最近更新 更多