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

文章目录

      • 一、run
      • 二、Popen

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 andstderr. By default, stdout and stderr are not captured, and those attributeswill 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 aCalledProcessError. The CalledProcessError object will have the return codein the returncode attribute, and output & stderr attributes if those streamswere captured.# timeout is not None, 且进程耗时过长, 抛出 TimeoutExpired 异常, 停止 subprocess和父进程If timeout is given, and the process takes too long, a TimeoutExpiredexception will be raised.# 可选参数 input 传递字节/字符串给 subprocess.Popen() 的 stdin. # 意味着 input 和 stdin 参数不能同时使用, 抛出 ValueError 异常.There is an optional argument "input", allowing you topass bytes or a string to the subprocess's stdin.  If you use this argumentyou may not also use the Popen constructor's "stdin" argument, asit 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" shouldbe 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 decodedaccording to locale encoding, or by "encoding" if set. Text mode istriggered 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.|      等待子进程终止; 返回状态码

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/584488.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

第二百三十五回

文章目录 概念介绍使用方法示例代码 我们在上一章回中介绍了PopupMenuButton相关的内容&#xff0c;本章回中将介绍如何在任意位置显示PopupMenu.闲话休提&#xff0c;让我们一起Talk Flutter吧。 概念介绍 我们在上一章回中介绍了PopupMenuButton相关的内容&#xff0c;它主要…

Alibaba Cloud Linux 3.2104 LTS 64位系统可以选择吗?

阿里云Alibaba Cloud Linux 3.2104 LTS 64位镜像是可以选择的&#xff0c;它阿里云打造的Linux服务器操作系统发行版&#xff0c;针对云服务器ECS做了大量深度优化&#xff0c;完全兼容RHEL/CentOS生态和操作方式&#xff0c;如果是阿里云服务器ECS建议选择Alibaba Cloud Linux…

嵌入式开发——GD32F4之ADC查询

通道 ADC0 ADC1 ADC2 IN0 PA0 PA0 PA0 IN1 PA1 PA1 PA1 IN2 PA2 PA2 PA2 IN3 PA3 PA3 PA3 IN4

QGraphicsItem器件移动及旋转相关问题

一、前言 Qt的图形视图框架中&#xff0c;可以使用如下接口设置图元坐标&#xff1a; void QGraphicsItem::setPos(const QPointF &pos)Sets the position of the item to pos, which is in parent coordinates. For items with no parent, pos is in scene coordinates.…

【数据结构】排序之插入排序

排序目录 1.前言2. 排序的概念及其运用2.1 排序的概念2.2 排序的运用2.3 常见的排序算法 3. 插入排序3.1 基本思想3.2 直接插入排序3.2.1 直接插入排序实现3.2.1.1 分析3.2.1.2 代码实现 3.3 希尔排序3.3.1 希尔排序实现3.3.1.1 分析3.3.1.2 代码实现 4. 附代码4.1 sort.h4.2 s…

golang基础学习以及代码实例

一、Go语言基础 这是我整理非常全的go语言基础知识点以及代码实例&#xff0c;对GO有情趣的同学可以通过这个总结以及代码实例快速入门&#xff01;加油同学们&#xff01; 1 Go介绍 是Google开发的一种静态强类型、编译型、并发型&#xff0c;并具有垃圾回收功能的编程语言…

Lumerical------按键中断程序执行

Lumerical------中断程序执行 引言正文 引言 在 Lumerical 中&#xff0c;很多时候我们需要通过 sweep 的方式来获取我们想要的结果&#xff0c;然而&#xff0c;有时候当我们运行程序后发现书写的脚本有问题时&#xff0c;我们想要强行终止程序的执行&#xff0c;该怎么办呢&…

一次JAVA调用C++的.so库的过程

1、准备好.so文件 2、java代码引入jna jar包 <dependency><groupId>net.java.dev.jna</groupId><artifactId>jna</artifactId><version>5.9.0</version> </dependency>3、代码实现 package com.jimi.tracker.util;import c…

Linux文件系统中的目录

目录说明/Linux操作系统所有目录的入口binbinaries缩写&#xff0c;存放二进制可执行文件sbinsuperuser binaries缩写&#xff0c;存放二进制可执行文件&#xff0c;只有root才能访问etcetcetera缩写&#xff0c;存放系统配置文件usrunix sharedresources缩写&#xff0c;用于存…

K8s攻击案例:组件未授权访问导致集群入侵

K8s集群往往会因为组件的不安全配置存在未授权访问的情况&#xff0c;如果攻击者能够进行未授权访问&#xff0c;可能导致集群节点遭受入侵。比较常见的的组件未授权访问漏洞&#xff0c;主要包括 API Server 未授权访问、kubelet 未授权访问、etcd 未授权访问、kube-proxy 不安…

C++系列-第1章顺序结构-4-整型int

C系列-第1章顺序结构-4-整型int 在线练习&#xff1a; http://noi.openjudge.cn/ https://www.luogu.com.cn/ 总结 本文是C系列博客&#xff0c;主要讲述整型int的用法 整型int 在C中&#xff0c;int 是一个关键字&#xff0c;用于声明整型变量。int 类型用于存储整数&…

01的token的年度总结

​ 大家好&#xff0c;我是token&#xff0c;一个热爱.NET的普通人&#xff0c;同样我来自湖南衡阳&#xff0c;再次之前我已经遇到非常多的湖南衡阳的老乡&#xff0c;比如李哥。 ​ 在这里一年中&#xff0c;我的成长也是非常迅速的&#xff0c;每一年的的每一天&#xff0c…

【Linux】深挖进程地址空间

> 作者简介&#xff1a;დ旧言~&#xff0c;目前大二&#xff0c;现在学习Java&#xff0c;c&#xff0c;c&#xff0c;Python等 > 座右铭&#xff1a;松树千年终是朽&#xff0c;槿花一日自为荣。 > 目标&#xff1a;熟悉【Linux】进程地址空间 > 毒鸡汤&#xff…

Thinkphp+vue+mysql学生作业管理系统21j0r

运行环境:phpstudy/wamp/xammp等 开发语言&#xff1a;php 后端框架&#xff1a;Thinkphp5 前端框架&#xff1a;vue.js 服务器&#xff1a;apache 数据库&#xff1a;mysql 数据库工具&#xff1a;Navicat/phpmyadmin 为设计一个安全便捷&#xff0c;并且使用户更好获取本学院…

解决jenkins、git拉取代码仓库失败Please make sure you have the correct access rights

更多ruoyi-nbcio功能请看演示系统 gitee源代码地址 前后端代码&#xff1a; https://gitee.com/nbacheng/ruoyi-nbcio 演示地址&#xff1a;RuoYi-Nbcio后台管理系统 更多nbcio-boot功能请看演示系统 gitee源代码地址 后端代码&#xff1a; https://gitee.com/nbacheng/n…

Redis主从

一、为何需要主从 单节点Redis的并发能力是有上限的&#xff0c;要进一步提高Redis的并发能力&#xff0c;就需要搭建主从集群&#xff0c;实现读写分离 二、如何设置主从 有临时和永久两种模式&#xff1a; 修改配置文件&#xff08;永久生效&#xff09; 在redis.conf中添…

C语言计算三阶行列式

文章目录 1-13题例题14参考答案1参考答案2 1-13题 C语言基础例题1-3题-指针篇 C语言基础例题4-5题-二维数组篇 C语言基础例题6-7题-结构体篇 C语言基础例题8-9题-大作业篇 C语言基础例题10-11题-字符串、指针篇 C语言基础例题12题-链表 C语言基础例题13题-字符串逆序 例题14 …

oracle怎么创建反向索引,解决enq:TX - index contention

有时候发生激烈的索引竞争的话&#xff0c;例如有大量的等待事件&#xff1a;enq&#xff1a;TX - index contention&#xff0c;此时可能需要创建反向索引解决&#xff0c;那么如何创建呢&#xff1f;下面是创建反向索引的实验过程&#xff1a; – 创建两张相同结构的表&…

【23.12.29期--Spring篇】Spring的 IOC 介绍

介绍一下Spring的IOC ✔️引言✔️ lOC的优点✔️Spring的IOC✔️ 拓展知识仓✔️IOC是如何实现的&#xff1f; ✔️引言 所谓的IOC (inversion of control) &#xff0c;就是控制反转的意思。何为控制反转? 在传统的程序设计中&#xff0c;应用程序代码通常控制着对象的创建和…

Typora使用PicGo+Gitee上传图片

Typora使用PicGoGitee上传图片 1.下载PicGo(国内镜像) https://mirrors.sdu.edu.cn/github-release/Molunerfinn_PicGo/ 点击PicGo-Setup-2.3.0-x64.exe &#xff08;64位安装&#xff09; 然后打开gitee&#xff08;没注册先注册&#xff09; 2.下载node.js插件 https:/…