【问题标题】:making python 2.2 show stdout and saving to file使 python 2.2 显示标准输出并保存到文件
【发布时间】:2012-07-13 20:22:45
【问题描述】:

我正在尝试编写一个执行一堆其他脚本的 python 脚本。我想这样当脚本运行时,该脚本的输出显示在屏幕上,但如果遇到错误的退出状态,它将获取输出并将其附加到日志文件中。我试图使用“命令”界面,但这不允许您查看标准输出以及保存要附加到文件的数据。请注意,我使用的是 python 2.2(是的,它很旧,但我必须使用我得到的东西)。

谢谢。

示例代码:(虽然没有做我想做的事)

def run_functional_analysis(script, now):
    stat, output = commands.getstatusoutput(script_dir + script + " -fb")
    if stat!=0: #If the script failed:
        os.system("echo \"[" + now + "] - " + output + "\" >> " + LOG_DIR + script + ".log")

【问题讨论】:

  • 向我们展示您的代码。到目前为止,您尝试过什么?
  • 已编辑,但没有做我想做的事情(它只是将错误复制到文件中,不会同时显示输出)
  • 打印输出将在命令完成后简单地打印输出。我希望它在运行时同时打印。

标签: python subprocess stdout


【解决方案1】:

Python 2.2 已经很老了。如果可以的话,你应该升级,因为subprocess 确实比os.systemos.popen 好很多。

您想要的是一个类似文件的对象,它既可以写入stdout,又可以捕获到字符串(可能使用StringIO)。然后您可以在subprocess 中将该对象指定为stdoutstderr来电。

import sys, subprocess
from cStringIO import StringIO

class Outcap(object):
    def __init__(self):
        self.output = StringIO()
    def write(self, data):
        sys.stdout.write(data)
        self.output.write(data)
    def flush(self):
        sys.stdout.flush(data)
    def close(self):
        pass

    @property
    def text(self):
        return self.output.getvalue()

outcap = Outcap()

try:
    subprocess.check_call("foo bar baz".split(), stdout=outcap, stderr=outcap)
    subprocess.check_call("one two three".split(), stdout=outcap, stderr=outcap)
except CalledProcessError as e:
    outcap.write("return code: %s\n", e.returncode)
    open("log.txt", "w").write(outcap.text)

如果您无法升级您的 Python,但您使用的是 Linux,则另一种选择是在 Python 之外通过tee 命令传递您正在运行的命令来处理它。

your command goes here 2>&1 | tee log.txt

这会将您的命令的所有输出保存到log.txt,并将其发送到标准输出。你从那里选择用它做什么取决于你的 Python 脚本。例如,您可以登录到一个临时文件,然后仅在其中一个命令失败时将其移动到永久位置。

【讨论】:

  • 哇,我刚刚意识到 python 2.2 甚至没有子进程。我认为它有一个非常小的版本。您是否有任何提示可以在没有子流程的情况下执行此操作?我将在上面进行编辑。
  • 是的,我在意识到 Python 2.2 没有 subprocess 之前写了所有这些。我在里面放了一个替代品。
  • 所以我试过了,我得到一个错误,上面写着:grep: writing output: Broken pipe
  • 这是一个shell错误;很难说是什么原因导致它没有看到你最终执行的确切命令行。
  • 如果我尝试在 shell(不使用 python)上运行该命令,我会收到一条错误消息,显示“不明确的输出重定向”。跟剧本有关系吗?编辑:我想我可能知道问题是什么,但我可能是错的。我的 shell 类型显然是 csh。所以我敢肯定,如果我通过python执行事情,它也在csh中执行。所以它可能无法识别上面的重定向。
猜你喜欢
  • 1970-01-01
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-26
  • 2022-01-17
  • 2011-03-12
  • 2016-12-04
相关资源
最近更新 更多