Is there a quiet version of subprocess.call?

后端 未结 4 1638
渐次进展
渐次进展 2020-12-10 10:27

Is there a variant of subprocess.call that can run the command without printing to standard out, or a way to block out it\'s standard out messages?

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 10:55

    This is a recipe I use a lot: call subprocess and collect the output, and when the command succeeds discard the output, but when it fails print the output.

    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
    

提交回复
热议问题