在stdout文件和cons中打印结果

2024-04-23 10:52:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我的要求是在控制台中打印文件的输出以及日志文件。下面的代码为我做了这件事,除了一个小问题。我在文件末尾调用一个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()

有谁能告诉我如何才能做到这一点?还是有可能实现?在


Tags: 文件代码importselfobjloggingdefstdout
3条回答

如果您看一下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

使用^{}

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

在Python2.6中,要么使用后台端口^{},要么复制2.7 source for ^{}。在

下面的代码帮了我一把。谢谢大家的帮助。在

#!/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()

相关问题 更多 >