【问题标题】:How can I get terminal output in python? [duplicate]如何在 python 中获取终端输出? [复制]
【发布时间】:2011-05-23 10:38:51
【问题描述】:

我可以使用os.system() 执行终端命令,但我想捕获此命令的输出。我该怎么做?

【问题讨论】:

    标签: python terminal


    【解决方案1】:
    >>> import subprocess
    >>> cmd = [ 'echo', 'arg1', 'arg2' ]
    >>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
    >>> print output
    arg1 arg2
    

    使用 subprocess.PIPE 时存在错误。对于巨大的输出使用这个:

    import subprocess
    import tempfile
    
    with tempfile.TemporaryFile() as tempf:
        proc = subprocess.Popen(['echo', 'a', 'b'], stdout=tempf)
        proc.wait()
        tempf.seek(0)
        print tempf.read()
    

    【讨论】:

    • 你是我的救星!!!这几天我一直在找这样的东西!!!谢谢!
    【解决方案2】:

    Python 3.5 及以上版本推荐使用subprocess.run():

    from subprocess import run
    output = run("pwd", capture_output=True).stdout
    

    【讨论】:

    • 管道未定义
    • @Cherona 是在subprocess 模块中定义的,所以需要导入。
    • 我还使用最新的 API 更新了答案。
    • @HelenCraigman 我明白了。在 Unix 上,您仍然可以通过打开 /dev/tty 进行读取和写入来从“控制终端”读取。不过,我不确定这种模式是否是个好主意。
    • FileNotFoundError: [WinError 2] 系统找不到指定的文件
    【解决方案3】:

    您可以按照他们的建议在subprocess 中使用Popen

    os,不推荐,如下:

    import os
    a  = os.popen('pwd').readlines()
    

    【讨论】:

    • 这不起作用。 Popen 对象没有 readlines() 方法。
    • 感谢指出,它只适用于os.popen
    • os.popen 已弃用,取而代之的是 subprocess.Popen
    【解决方案4】:

    最简单的方法是使用库命令

    import commands
    print commands.getstatusoutput('echo "test" | wc')
    

    【讨论】:

    • 从哪里获得命令模块?它似乎不在 Python3 的 pip 上。
    • @Shule commands 是一个较旧的模块。它被 subprocess 模块取代。 docs.python.org/2/library/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    相关资源
    最近更新 更多