python subprocess run 和 Popen 的一些使用和注意事项

2023-12-29 17:27:24

文章目录

NAME
subprocess - Subprocesses with accessible I/O streams

MODULE REFERENCE
https://docs.python.org/3.9/library/subprocess
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.

from subprocess import Popen, PIPE
from subprocess import run

python IDE 的提示反而看不懂, 因此需要了解一下内部实现细节更好理解和使用。

请添加图片描述

一、run

run() 方法是对 Popen() 方法的封装.

subprocess.run() 模块可供参考的初学者教程:https://www.dataquest.io/blog/python-subprocess/

run(*popenargs, input=None, capture_output=False, timeout=None, check=False, **kwargs)
    
    # 带参数运行命令, 并返回一个 CompletedProcess 实例.
    Run command with arguments and return a CompletedProcess instance.
    
    # 返回的实例将包含属性: process.args, ret_code, stdout, stderr.
    # 默认情况, stdout 和 stderr 不捕获, 值为 None; 传入参数 stdout=PIPE 和 stderr=PIPE 可以捕获它们.
    # capture_output=True 可以捕获, 但与 stdin/stdout 不能同时使用, 抛出 ValueError 异常
    # 程序出错时, stdout 将为 None, stderr 将包含错误信息.
    # 仅设置 capture_output=True 在subprocess出错时, subprocess 和父进程都不会停止, 即该行代码后续还会运行
    # 注意此时 result=run(...) 的 result 是 CompletedProcess 的内容
    The returned instance will have attributes args, returncode, stdout and
    stderr. By default, stdout and stderr are not captured, and those attributes
    will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them.
    
    # check=True 且 ret_code!=0 时, 抛出 CalledProcessError 异常
    # (含 ret_code, process.args, output(None), stderr(若选择捕获))
    # 注意此时 result=run(...) 的 result 是 None, 因为还没执行完提前抛出异常了, 该行后续代码不执行
    # CalledProcessError(1, ['ffmpeg', '-f', 'dshow', '-i', 'video="USB Video"', '-frames:v', '1', 'sn.jpg'])
    # 设置 check=True 后 subprocess 中任何错误都将导致 subprocess 和父进程停止
    If check is True and the exit code was non-zero, it raises a
    CalledProcessError. The CalledProcessError object will have the return code
    in the returncode attribute, and output & stderr attributes if those streams
    were captured.
    
    # timeout is not None, 且进程耗时过长, 抛出 TimeoutExpired 异常, 停止 subprocess和父进程
    If timeout is given, and the process takes too long, a TimeoutExpired
    exception will be raised.
    
    # 可选参数 input 传递字节/字符串给 subprocess.Popen() 的 stdin. 
    # 意味着 input 和 stdin 参数不能同时使用, 抛出 ValueError 异常.
    There is an optional argument "input", allowing you to
    pass bytes or a string to the subprocess's stdin.  If you use this argument
    you may not also use the Popen constructor's "stdin" argument, as
    it will be used internally.
    
    # 默认所有 communication 都是以 bytes 进行的, 因此 input/stdout/stderr 都将是 bytes.
    # 设置以下任一参数将触发 Text 模式: text/encoding/errors/universal_newlines
    # 文本(Text) 模式下, input 应该是 str, stdout/stderr 将会是根据区域编码(或根据encoding参数)进行解码后的字符串
    By default, all communication is in bytes, and therefore any "input" should
    be bytes, and the stdout and stderr will be bytes. If in text mode, any
    "input" should be a string, and stdout and stderr will be strings decoded
    according to locale encoding, or by "encoding" if set. Text mode is
    triggered by setting any of text, encoding, errors or universal_newlines.
    
    # 其他参数与 Popen 构造函数相同
    The other arguments are the same as for the Popen constructor.

二、Popen

class Popen(builtins.object)
 |  Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, user=None, group=None, extra_groups=None, encoding=None, errors=None, text=None, umask=-1)
 |  
 |  Execute a child program in a new process.在新进程中执行子程序。
 |  
 |  For a complete description of the arguments see the Python documentation.
 |  有关参数的完整描述,请参阅 Python 文档。
 |  
 |  Arguments: 参数
 |    args: A string, or a sequence of program arguments.
 |          一个字符串,或一系列程序参数。
 |  
 |    bufsize: supplied as the buffering argument to the open() function when
 |        creating the stdin/stdout/stderr pipe file objects
 |             在创建 stdin/stdout/stderr 管道文件对象时作为缓冲参数提供给 open() 函数
 |  
 |    executable: A replacement program to execute.
 |                要执行的替换程序。
 |  
 |    stdin, stdout and stderr: These specify the executed programs' standard
 |        input, standard output and standard error file handles, respectively.
 |                           它们分别指定了执行程序的标准输入、标准输出和标准错误文件句柄。
 |  
 |    preexec_fn: (POSIX only) An object to be called in the child process
 |        just before the child is executed.
 |               (仅限 POSIX)在执行子进程之前要在子进程中调用的对象。
 |  
 |    close_fds: Controls closing or inheriting of file descriptors.
 |               控制文件描述符的关闭或继承。
 |  
 |    shell: If true, the command will be executed through the shell.
 |           如果为真,命令将通过 shell 执行。
 |  
 |    cwd: Sets the current directory before the child is executed.
 |         在执行子进程之前设置当前目录。
 |  
 |    env: Defines the environment variables for the new process.
 |         为新进程定义环境变量。
 |  
 |    text: If true, decode stdin, stdout and stderr using the given encoding
 |        (if set) or the system default otherwise.
 |   如果为 true,则使用给定的编码(如果已设置)或系统默认值对 stdin、stdout 和 stderr 进行解码。
 |  
 |    universal_newlines: Alias of text, provided for backwards compatibility.
 |                        文本的别名,用于向后兼容。
 |  
 |    startupinfo and creationflags (Windows only)
 |  
 |    restore_signals (POSIX only)
 |  
 |    start_new_session (POSIX only)
 |  
 |    group (POSIX only)
 |  
 |    extra_groups (POSIX only)
 |  
 |    user (POSIX only)
 |  
 |    umask (POSIX only)
 |  
 |    pass_fds (POSIX only)
 |  
 |    encoding and errors: Text mode encoding and error handling to use for
 |        file objects stdin, stdout and stderr.
 |    编码和错误: 用于文件对象标准输入、标准输出和标准错误的文本模式编码和错误处理。
 |  
 |  Attributes:
 |      stdin, stdout, stderr, pid, returncode
 |      标准输入, 标准输出, 标准错误, 进程号, 返回码
 |  
 |  Methods defined here: 定义的方法如下
 |  
 |  __del__(self, _maxsize=9223372036854775807, _warn=<built-in function warn>)
 |  
 |  __enter__(self)
 |  
 |  __exit__(self, exc_type, value, traceback)
 |  
 |  __init__(self, args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, user=None, group=None, extra_groups=None, encoding=None, errors=None, text=None, umask=-1)
 |      Create new Popen instance.创建新的 Popen 实例。
 |  
 |  __repr__(self)
 |      Return repr(self).
 |  
 |  communicate(self, input=None, timeout=None)
 |      Interact with process: Send data to stdin and close it.
 |      Read data from stdout and stderr, until end-of-file is
 |      reached.  Wait for process to terminate.
 |      与进程交互:将数据发送到标准输入并关闭它。
 |      从 stdout 和 stderr 读取数据,直到到达文件末尾。 等待进程终止。
 |      
 |      The optional "input" argument should be data to be sent to the
 |      child process, or None, if no data should be sent to the child.
 |      communicate() returns a tuple (stdout, stderr).
 |      可选的 "input" 参数应该是要发送给子进程的数据,如果没有数据要发送给子进程,则为 None。
 |      communicate() 返回一个元组(stdout,stderr)。
 |      
 |      By default, all communication is in bytes, and therefore any
 |      "input" should be bytes, and the (stdout, stderr) will be bytes.
 |      If in text mode (indicated by self.text_mode), any "input" should
 |      be a string, and (stdout, stderr) will be strings decoded
 |      according to locale encoding, or by "encoding" if set. Text mode
 |      is triggered by setting any of text, encoding, errors or
 |      universal_newlines.
 |      默认情况下,所有通信都以字节为单位,因此任何 "input" 都应该是字节,(stdout, stderr)也是。
 |      如果在文本模式下(由 self.text_mode 指示),任何 "input" 都应该是一个字符串,并且
 |      (stdout, stderr) 将是根据语言环境编码解码的字符串,或者如果已设置则通过“编码”解码。
 |      通过设置文本、编码、错误或 universal_newlines 中的任何一个来触发文本模式。
 |  
 |  kill = terminate(self)
 |  
 |  poll(self)
 |      Check if child process has terminated. Set and return returncode
 |      attribute.
 |      检查子进程是否终止. 设置并返回返回码属性.
 |  
 |  send_signal(self, sig)
 |      Send a signal to the process.
 |      给进程发信号.
 |  
 |  terminate(self)
 |      Terminates the process.
 |      终止进程.
 |  
 |  wait(self, timeout=None)
 |      Wait for child process to terminate; returns self.returncode.
 |      等待子进程终止; 返回状态码

文章来源:https://blog.csdn.net/qq_27677599/article/details/135292320
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。