72

標準出力に出力せずにコマンドを実行できるバリアントsubprocess.call、または標準出力メッセージをブロックする方法はありますか?

4

4 に答える 4

80

はい。にリダイレクトstdout/dev/nullます。

process = subprocess.call(["my", "command"], stdout=open(os.devnull, 'wb'))
于 2011-12-16T03:27:11.623 に答える
47

多くの場合、そのようなおしゃべりがstderrで発生するため、それも沈黙させることができます。Python 3.3以降、subprocess.callこの機能は直接あります。

stdoutまたはstderrを抑制するには、DEVNULLの値を指定します。

使用法:

import subprocess
rc = subprocess.call(args, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)

まだPython2を使用している場合:

import os, subprocess

with open(os.devnull, 'wb') as shutup:
    rc = subprocess.call(args, stdout=shutup, stderr=shutup)
于 2011-12-16T03:57:26.220 に答える
-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
于 2013-05-08T02:05:40.070 に答える
-1

そのような場合はsubprocess.check_outputを使用し、戻り値を削除します。check_callの代わりにcheck_outputを使用している理由を示すコメントをコードに追加することをお勧めします。check_outputは、障害が発生し、エラー出力に関心がある場合にも適しています。以下のサンプルコード。印刷行のコメントを解除した場合にのみ、出力が表示されます。コマンドが失敗すると、例外がスローされます。

import subprocess
ret = subprocess.check_output(["cat", "/tmp/1"])
#print ret
于 2015-03-29T15:14:13.013 に答える