Home  >  Article  >  Backend Development  >  Introduction to subprocess module-level methods in python (with code)

Introduction to subprocess module-level methods in python (with code)

不言
不言forward
2019-03-27 09:48:033093browse

This article brings you an introduction to the subprocess module-level method in Python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

subprocess.run()

Run and wait for the instruction specified by the args parameter to complete, and return the CompletedProcess instance.

Parameters: (*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs). Except for input, capture_output, timeout, and check, other parameters are consistent with the Popen constructor parameters.

capture_output: If set to True, it means redirecting stdout and stderr to the pipe, and no more stderr or stdout parameters can be passed, otherwise an exception will be thrown.

Input: The input parameter will be passed to the Popen.communicate() method as the standard input of the subprocess, and must be of string (encoding or errors parameters need to be specified, or text is set to True) or byte type. Non-None input parameters cannot be used together with stdin parameters, otherwise an exception will be thrown, and the stdin parameter used to construct the Popen instance will be specified as subprocess.PIPE.

timeout: passed to the Popen.communicate() method.

check: If set to True, a CalledProcessError exception will be thrown if the process execution returns a non-0 status code.

# 源码

def run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs):
    if input is not None:
        if 'stdin' in kwargs:
            raise ValueError('stdin and input arguments may not both be used.')
        kwargs['stdin'] = PIPE
    
    if capture_output:
        if ('stdout' in kwargs) or ('stderr' in kwargs):
            raise ValueError('stdout and stderr arguments may not be used '
                             'with capture_output.')
        kwargs['stdout'] = PIPE
        kwargs['stderr'] = PIPE
    
    with Popen(*popenargs, **kwargs) as process:
        try:
            stdout, stderr = process.communicate(input, timeout=timeout)
        except TimeoutExpired:
            process.kill()
            stdout, stderr = process.communicate()
            raise TimeoutExpired(process.args, timeout, output=stdout,
                                 stderr=stderr)
        except:  # Including KeyboardInterrupt, communicate handled that.
            process.kill()
            # We don't call process.wait() as .__exit__ does that for us.
            raise
        retcode = process.poll()
        if check and retcode:
            raise CalledProcessError(retcode, process.args,
                                     output=stdout, stderr=stderr)
    return CompletedProcess(process.args, retcode, stdout, stderr)

Before python3.5, the three methods call(), check_all(), and checkoutput() constituted the high-level API of the subprocess module.

subprocess.call()

Run and wait for the instruction specified by the args parameter to complete, and return the execution status code (returncode attribute of the Popen instance).

Parameters: (*popenargs, timeout=None, **kwargs). Basically the same as the Popen constructor parameters, all parameters except timeout will be passed to the Popen interface.

Do not use stdout=PIPE or stderr=PIPE when calling the call() function, because if the child process generates enough output to the pipe to fill the OS pipe buffer, the child process will be unable to read data from the pipe. And cause obstruction.

# 源码

def call(*popenargs, timeout=None, **kwargs):
    with Popen(*popenargs, **kwargs) as p:
        try:
            return p.wait(timeout=timeout)
        except:
            p.kill()
            p.wait()
            raise

subprocess.check_call()

Run and wait for the instruction specified by the args parameter to complete, return a 0 status code or throw a CalledProcessError exception. The cmd and returncode attributes of the exception can view the execution exception Instructions and status codes.

Parameters: (*popenargs, **kwargs). All parameters are passed to the call() function.

Notes are the same as call()

# 源码

def check_call(*popenargs, **kwargs):
    retcode = call(*popenargs, **kwargs)
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        raise CalledProcessError(retcode, cmd)
    return 0

subprocess.check_output()

Run and wait for the instruction specified by the args parameter to complete, and return to the standard output (stdout attribute of the CompletedProcess instance) , the type defaults to byte. The byte encoding may depend on the executed instruction. Setting universal_newlines=True can return a value of type string.
If the execution status code is non-0, a CalledProcessError exception will be thrown.

Parameters: (*popenargs, timeout=None, **kwargs). All arguments are passed to the run() function, but explicitly passing input=None to inherit the standard input file handle of the parent process is not supported.

To capture standard error in the return value, set stderr=subprocess.STDOUT; you can also redirect standard error to the pipe stderr=subprocess.PIPE, accessed through the stderr attribute of the CalledProcessError exception.

# 源码

def check_output(*popenargs, timeout=None, **kwargs):
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')

    if 'input' in kwargs and kwargs['input'] is None:
        # Explicitly passing input=None was previously equivalent to passing an
        # empty string. That is maintained here for backwards compatibility.
        kwargs['input'] = '' if kwargs.get('universal_newlines', False) else b''

    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
               **kwargs).stdout

The subprocess module also provides related functions of the commands module in the python2.x version.

subprocess.getstatusoutput(cmd)

Actually calls the check_output() function, executes the string type cmd instruction in the shell, and returns a tuple in the form of (exitcode, output), output( Contains stderr and stdout) is a string decoded using locale encoding with the trailing newline removed.

# 源码

try:
    data = check_output(cmd, shell=True, universal_newlines=True, stderr=STDOUT)
    exitcode = 0
except CalledProcessError as ex:
    data = ex.output
    exitcode = ex.returncode
if data[-1:] == '\n':
    data = data[:-1]
return exitcode, data

subprocess.getoutput(cmd)

Similar to getstatusoutput(), but the result only returns output.

This article has ended here. For more other exciting content, you can pay attention to the python video tutorial column of the PHP Chinese website!

The above is the detailed content of Introduction to subprocess module-level methods in python (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete