是否有一个安静的subprocess.call版本?

时间:2011-12-16 03:23:24

标签: python subprocess silent

是否有subprocess.call的变体可以在不打印到标准输出的情况下运行命令,或者阻止标准输出消息的方法?

5 个答案:

答案 0 :(得分:62)

是。将其stdout重定向到/dev/null

process = subprocess.call(["my", "command"], stdout=open(os.devnull, 'wb'))

答案 1 :(得分:29)

这种聊天常常在stderr上,所以你也可能想要沉默。这是我的例子:

from subprocess import call, DEVNULL
return_code = call(args, stderr=DEVNULL, stdout=DEVNULL)

注意: subprocess.DEVNULL自Python 3.3起可用。如果你还在使用Python 2:

import os

with open(os.devnull, 'w') as shutup:
    return_code = call(args, stdout=shutup, stderr=shutup)

答案 2 :(得分:10)

subprocess.call也接受stdin / stdout / stderr重定向:

process = subprocess.call(["my", "command"], stdout=open(os.devnull, 'wb'))

答案 3 :(得分:1)

这是我经常使用的一个配方:调用subprocess并收集输出,当命令成功时丢弃输出,但是当它失败时打印输出。

import subprocess as sp
import sys

if "print" in __builtins__.__dict__:
    prn = __builtins__.__dict__["print"]
else:
    def prn(*args, **kwargs):
        """
        prn(value, ..., sep=' ', end='\\n', file=sys.stdout)
        Works just like the print function in Python 3.x but can be used in 2.x.

        Prints the values to a stream, or to sys.stdout by default.
        Optional keyword arguments:
        file: a file-like object (stream); defaults to the current sys.stdout.
        sep:  string inserted between values, default a space.
        end:  string appended after the last value, default a newline.
        """
        sep = kwargs.get("sep", ' ')
        end = kwargs.get("end", '\n')
        file = kwargs.get("file", sys.stdout)

        s = sep.join(str(x) for x in args) + end
        file.write(s)


def rc_run_cmd_basic(lst_cmd, verbose=False, silent=False):
    if silent and verbose:
        raise ValueError("cannot specify both verbose and silent as true")

    p = sp.Popen(lst_cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
    tup_output = p.communicate()

    s_cmd = ' '.join(lst_cmd)
    if verbose:
        prn()
        prn("command: '%s'\n" % s_cmd)

        if 0 != p.returncode:
            prn()
            prn("Command failed with code %d:" % p.returncode)
        else:
            prn("Command succeeded!  code %d" % p.returncode)
    if verbose:
        prn("Output for: " + s_cmd)
        prn(tup_output[0])
        prn()
    if not silent and 0 != p.returncode:
        prn("Error output for: " + s_cmd)
        prn(tup_output[1])
        prn()

    return p.returncode

答案 4 :(得分:1)

在这种情况下我使用subprocess.check_output并删除返回值。您可能希望在代码中添加注释,说明为什么使用check_output代替check_call。如果发生故障并且您对错误输出感兴趣,check_output也会更好。示例代码如下。仅在取消注释打印行时才能看到输出。如果命令失败,则抛出异常。

import subprocess
ret = subprocess.check_output(["cat", "/tmp/1"])
#print ret