打印结果在stdout文件和控制台

时间:2013-07-09 01:30:39

标签: python logging printing python-2.6

我的要求是在控制台中打印文件的输出以及日志文件。下面这段代码对我来说是一个小问题。我在文件末尾调用一个perl脚本,其输出显示在控制台中,但不会打印到文件中。

import subprocess
import sys
class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)

f = open('MyFile.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "Logging Started"
# My code
print "A"

subprocess.call(['./MyScript])
sys.stdout = original
print "Logging Stopped"  # Only on stdout
f.close()

任何人都可以建议如何实现这一目标?或者是否有可能实现同样的目标?

4 个答案:

答案 0 :(得分:1)

使用subprocess.check_output

print subprocess.check_output(['./MyScript])

在Python 2.6中,使用backport subprocess32或复制2.7 source for check_output

答案 1 :(得分:0)

如果你看看check_output是否在Python2.7中实现,你应该能够找出如何使用subprocess.Popen

def check_output(*popenargs, **kwargs):
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
    output, unused_err = process.communicate()
    retcode = process.poll()
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        raise CalledProcessError(retcode, cmd, output=output)
    return output

答案 2 :(得分:0)

以下代码为我做了诀窍。谢谢大家的帮助。

#!/usr/bin/python
import os
import subprocess
import sys
class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)

f = open('MyFile.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "Logging Started"
# My code
print "A"

def check_output(*popenargs, **kwargs):
    process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
    output, unused_err = process.communicate()
    retcode = process.poll()
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        error = subprocess.CalledProcessError(retcode, cmd)
        error.output = output
        raise error
    return output

location = "%s/folder"%(os.environ["Home"])
myoutput = check_output(['./MyFile'])
print myoutput
sys.stdout = original
print "Logging Stopped"  # Only on stdout
f.close()

答案 3 :(得分:-1)

subprocess.check_ouput

是在python 2.7中引入的,如果你可以使用以前的版本,你可以使用Popen并将stdout设置为输出流(但在你的情况下,你已经覆盖了sys.stdout,我认为不需要),只需改为:

p = subprocess.Popen(['./MyScript'])