python子进程模块subprocess详解与应用实例 之二

从“要啥”到“咋测”:手把手拆解Aspice SWE.1需求分析,为你的车载/嵌入式项目避坑 本文深入解析Aspice SWE.1需求分析在车载/嵌入式项目中的关键作用,帮助开发者将模糊的系统需求转化为可执行、可验证的软件需求。通过实战案例和结构化方法,详细拆解功能需求原子化、非功能需求工程化表达等核心技巧,为项目避坑提供实用指南。 阅读详情

1.2. Popen 对象

Popen类的实例有下列方法:
1. Popen.poll()
检查子进程是否已经结束,设置并返回返回码值。
2. Popen.wait()
等待子进程结束,设置并返回返回码值。
WARNING: 当使用 stdout=PIPE 或 stderr=PIPE 并且子进程生成了足够多的输出信息到管道,以至于管道阻塞,将会造成死锁。
         使用 communicate()可以避免这种情况。
3. Popen.communicate(input=None)
和子进程进行交互: 发送数据到stdin, 从stdout和 stderr读取数据,直到遇到 end-of-file。等待子进程结束。
可选的 input 参数是一个传送给子进程的字符串,或 None。
communicate() 返回一个元组(stdoutdata, stderrdata).
NOTE: 如果想发送数据到子进程的 stdin, 需要设置 stdin=PIPE并创建Popen对象。
      相似的,要想获得返回结果元组中的非空值,需要设置 stdout=PIPE或 stderr=PIPE.
      实际上,读取的数据是缓冲在内存中,因此,如果数据太大或无限时不要使用这个上方法。
4. Popen.send_signal(signal)
发送一个信号 signal到子进程。
NOTE: 在Windows中, SIGTERM是terminate()的别名。
5. Popen.terminate()
停止子程序,在Posix操作系统中,这个方法发送的是SIGTERM到子程序。
6. Popen.kill()
杀死子进程,在Posix操作系统中,这个上函数发送SIGKILL给子进程。

下面的属性也是同样有效的:
WARNING: 使用communicate()而不是 .stdin.write, .stdout.read 或 stderr.read,可以避免因管道阻塞而造成的死锁。
1. Popen.stdin
如果参数值为 PIPE, 那么这个属性值是一个文件对象,用来提供子进程的输入。
否则,它的值 为 None.
2. Popen.stdout
如果参数值为 PIPE, 那么这个属性值是一个文件对象,它提供了子进程的输出。
否则,值为 None
3. Popen.stderr
If the stderr argument was PIPE, this attribute is a file object that provides error output from the child process. 
Otherwise, it is None.
4. Popen.pid
子进程的进程ID
Note that if you set the shell argument to True, this is the process ID of the spawned shell.
5. Popen.returncode
子进程的返回码,由poll()和wait()设置(并间接由 communicate()设置)。
非零值表示子进程还没有被结束。
负值 -N 表示子进程被信号N结束。

1.3. Windows Popen 使用

The STARTUPINFO class and following constants are only available on Windows.
1. class subprocess.STARTUPINFO
   Partial support of the Windows STARTUPINFO structure is used for Popen creation.
2. dwFlags
A bit field that determines whether certain STARTUPINFO attributes are used when the process creates a window.
   si = subprocess.STARTUPINFO()
   si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
3. hStdInput
If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard input handle for the process. If 
STARTF_USESTDHANDLES is not specified, the default for standard input is the keyboard buffer.
4. hStdOutput
If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard output handle for the process. Otherwise, 
this attribute is ignored and the default for standard output is the console window’s buffer.
5. hStdError
If dwFlags specifies STARTF_USESTDHANDLES, this attribute is the standard error handle for the process. Otherwise, 
this attribute is ignored and the default for standard error is the console window’s buffer.
6. wShowWindow
If dwFlags specifies STARTF_USESHOWWINDOW, this attribute can be any of the values that can be specified in the 
nCmdShow parameter for the ShowWindow function, except for SW_SHOWDEFAULT. Otherwise, this attribute is ignored.
7. SW_HIDE is provided for this attribute. It is used when Popen is called with shell=True.
1.3.1. 常量
The subprocess module exposes the following constants.
subprocess.STD_INPUT_HANDLE
The standard input device. Initially, this is the console input buffer, CONIN$.
subprocess.STD_OUTPUT_HANDLE
The standard output device. Initially, this is the active console screen buffer, CONOUT$.
subprocess.STD_ERROR_HANDLE
The standard error device. Initially, this is the active console screen buffer, CONOUT$.
subprocess.SW_HIDE
Hides the window. Another window will be activated.
subprocess.STARTF_USESTDHANDLES
Specifies that the STARTUPINFO.hStdInput, STARTUPINFO.hStdOutput, and STARTUPINFO.hStdError attributes contain 
additional information.
subprocess.STARTF_USESHOWWINDOW
Specifies that the STARTUPINFO.wShowWindow attribute contains additional information.
subprocess.CREATE_NEW_CONSOLE
The new process has a new console, instead of inheriting its parent’s console (the default).
This flag is always set when Popen is created with shell=True.
subprocess.CREATE_NEW_PROCESS_GROUP
A Popen creationflags parameter to specify that a new process group will be created. 
This flag is necessary for using os.kill() on the subprocess
This flag is ignored if CREATE_NEW_CONSOLE is specified.

1.4. 使用 subprocess模块代替旧函数 

In this section, “a becomes b” means that b can be used as a replacement for a.
Note All “a” functions in this section fail (more or less) silently if the executed program cannot be found;
the “b” replacements raise OSError instead.
In addition, the replacements using check_output() will fail with a CalledProcessError if the requested operation 
produces a non-zero return code. The output is still available as the output attribute of the raised exception.
In the following examples, we assume that the relevant functions have already been imported from the subprocess 
module.
1.4.1. Replacing /bin/sh shell backquote
output=`mycmd myarg`
# becomes
output = check_output(["mycmd", "myarg"])
1.4.2. Replacing shell pipeline
output=`dmesg | grep hda`
# becomes
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
The p1.stdout.close() call after starting the p2 is important in order for p1 to receive a SIGPIPE if p2 exits before p1.
Alternatively, for trusted input, the shell’s own pipeline support may still be used directly:
output=`dmesg | grep hda`
# becomes
output=check_output("dmesg | grep hda", shell=True)
1.4.3. Replacing os.system()
status = os.system("mycmd" + " myarg")
# becomes
status = subprocess.call("mycmd" + " myarg", shell=True)
Notes:
Calling the program through the shell is usually not required.
A more realistic example would look like this:
try:
    retcode = call("mycmd" + " myarg", shell=True)
    if retcode < 0:
        print >>sys.stderr, "Child was terminated by signal", -retcode
    else:
        print >>sys.stderr, "Child returned", retcode
except OSError as e:
    print >>sys.stderr, "Execution failed:", e
1.4.4. Replacing the os.spawn family
P_NOWAIT example:
pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid
P_WAIT example:
retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
==>
retcode = call(["/bin/mycmd", "myarg"])
Vector example:
os.spawnvp(os.P_NOWAIT, path, args)
==>
Popen([path] + args[1:])
Environment example:
os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
==>
Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}
1.4.5. Replacing os.popen(), os.popen2(), os.popen3()
pipe = os.popen("cmd", 'r', bufsize)
==>
pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
pipe = os.popen("cmd", 'w', bufsize)
==>
pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
(child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
(child_stdin,
 child_stdout,
 child_stderr) = os.popen3("cmd", mode, bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
(child_stdin,
 child_stdout,
 child_stderr) = (p.stdin, p.stdout, p.stderr)
(child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
                                                   bufsize)
==>
p = Popen("cmd", shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
(child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as the command to execute, in which case arguments 


will be passed directly to the program without shell intervention. This usage can be replaced as follows:


(child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
                                        bufsize)
==>
p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
Return code handling translates as follows:


pipe = os.popen("cmd", 'w')
...
rc = pipe.close()
if rc is not None and rc >> 8:
    print "There were some errors"
==>
process = Popen("cmd", 'w', shell=True, stdin=PIPE)
...
process.stdin.close()
if process.wait() != 0:
    print "There were some errors"
1.4.6. Replacing functions from the popen2 module
(child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
==>
p = Popen("somestring", shell=True, bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
On Unix, popen2 also accepts a sequence as the command to execute, in which case arguments will be passed directly to 
the program without shell intervention. This usage can be replaced as follows:
(child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,mode)​
==>
p = Popen(["mycmd", "myarg"], bufsize=bufsize,
          stdin=PIPE, stdout=PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
popen2.Popen3 and popen2.Popen4 basically work as subprocess.Popen, except that:
Popen raises an exception if the execution fails.
the capturestderr argument is replaced with the stderr argument.
stdin=PIPE and stdout=PIPE must be specified.
popen2 closes all file descriptors by default, but you have to specify close_fds=True with Popen.

1.5. NOTES

1.5.1. Converting an argument sequence to a string on Windows
On Windows, an args sequence is converted to a string that can be parsed using the following rules (which correspond 
to the rules used by the MS C runtime):

Arguments are delimited by white space, which is either a space or a tab.
A string surrounded by double quotation marks is interpreted as a single argument, regardless of white space 
contained within. A quoted string can be embedded in an argument.
A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.
Backslashes are interpreted literally, unless they immediately precede a double quotation mark.
If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal 
backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as 
described in rule 3.

保姆级教程:用OSSH免费版+FreeRADIUS+FreeAC NAC,从零搭建一套企业级无线Portal认证系统 本文提供了一套基于OSSH免费版、FreeRADIUS和FreeAC NAC的企业级无线Portal认证系统搭建教程。从环境规划、核心组件安装到认证策略与用户管理,详细介绍了如何利用开源工具构建高效、安全的认证体系,特别适用于预算有限但需求严格的企业场景。 阅读详情

相关推荐

Moltemplate建模----水盒子data文件

1功能介绍 Moltemplate是LAMMPS官方支持的建模工具之一,适用于LAMMPS建模。该程序创建了一种简单的文件格式来存储分子定义和力场,即模板LT。LT文件包含与特定分子有关的所有文本(包括坐标,键拓扑,角度,力场参数,约束,组和修复)。 Moltemplate可以复制分子,对其进行自定义,然后用它作为构建更大、更复杂分子的基础。构建后,可以自定义...

元素魔方科研服务 2595

Python subprocess.communicate()方法详解

Python subprocess.communicate()方法详解

Leon_Jinhai_Sun的博客 2725

HFSS螺旋线圈的优化设计与高效仿真实践

本文详细介绍了HFSS螺旋线圈的优化设计与高效仿真实践,涵盖核心参数设置、参数化建模、仿真加速技巧及结果分析。通过HFSS软件实现螺旋线圈的高效仿真,特别适用于无线充电和RFID系统设计,提升设计效率与性能验证准确性。

weixin_30235225的博客 445

Python Popen communicate() 和wait()的区别体验

测试环境centos7 ulimit -a 看到的 pipe size 是 4KB,那只是每页的大小,查询得知 linux 默认的 pipe size 是 64KB。 简单说communicate() 和wait()的区别,使用 subprocess 模块的 Popen 调用外部程序,如果 stdout 或 stderr 参数是 pipe,并且程序输出超过操作系统的 pipe size时,如果使用...

Neo 1万+

松材线虫病害智能检测:基于YOLOv8的无人机航拍数据集构建与模型优化

本文探讨了基于YOLOv8的无人机航拍技术在松材线虫病害智能检测中的应用。通过构建高质量巡检数据集和优化模型架构(如RepVit主干网络和跨尺度特征融合模块),显著提升了病害识别准确率。该方案在复杂森林环境中表现出色,将检测效率提高数倍,为林业病害防控提供了高效解决方案。

vulkan6gpu的博客 995

论文阅读:SuperGaussians: Enhancing Gaussian Splatting Using Primitives with Spatially Varying Colors

Gaussian Splattings 在基于高斯显式表示的多视图重建中展示出了令人印象深刻的结果。然而,当前的高斯基元只有单视图依赖的颜色和不透明度来表示场景的外观和几何形状,导致了一种非紧凑的表示。在本文中,我们引入了一种名为“超高斯(SuperGaussians)”的新方法,它在单个高斯基元中利用空间变化的颜色和不透明度来提高其表示能力。我们实现了双线性插值、移动核,甚至是小型神经网络作为空间变化函数。

m0_48319749的博客 1508

Python Popen communicate() 和wait()使用上的区别

之所以会纠结到这个问题上是因为发现在调用Popen的wait方法之后程序一直没有返回。google发现wait是有可能产生死锁的。为了把这个问题彻底弄清楚,搜索一些资料过来看看:   看到别人的例子: 今天遇到的一个问题。简单说就是,使用 subprocess 模块的 Popen 调用外部程序,如果 stdout 或 stderr 参数是 pipe,并且程序输出超过操作系统的 pipe

从菜鸟到菜菜鸟 9万+

手把手教你用WKT文件在Petrel中创建自定义坐标系统(附CGCS2000转换模板)

本文详细介绍了如何在Petrel软件中利用WKT文件创建自定义坐标系统,并重点提供了CGCS2000坐标系的完整转换模板与实战步骤。通过解析坐标系统的三大支柱(大地坐标系、投影坐标系、基准转换)和WKT文件结构,指导用户从零开始构建适用于本土化项目的坐标系统,确保地质建模与空间数据处理的精度与一致性。

gpt4scribbler的博客 279

Python 子进程 Popen.communicate() 等价于 Popen.stdout.read()?

1. Popen.communicate()方法会等待子进程执行完毕并返回一个元组,其中包含两个元素:第一个元素是标准输出的内容(包括错误信息),第二个元素是标准错误的内容。在Python中,Popen.communicate()方法和Popen.stdout.read()方法都可以用来读取子进程的输出流。2. Popen.stdout.read()方法会直接读取标准输出的内容,如果标准输出没有内容,那么它会返回一个空的字节串。# 使用stdout.read()方法获取子进程的输出内容。

880

J-SCOPE实战:除了看波形,如何用它和JLink-RTT模式高效调试你的STM32变量?

本文详细介绍了如何利用J-SCOPE和JLink-RTT模式高效调试STM32变量,实现实时数据可视化。通过对比HSS和RTT模式的优劣,提供固件端配置、J-SCOPE设置及实战应用案例,帮助开发者快速掌握这一高效调试技术,特别适用于电机控制、传感器融合等需要实时监控的场景。

weixin_29159613的博客 445

Xilinx实战-深入AXI UART Lite IP核的配置与调试

本文详细介绍了Xilinx FPGA中AXI UART Lite IP核的配置与调试方法,包括Vivado环境下的IP核设置、关键参数优化、寄存器操作及常见问题排查。通过实战案例和代码示例,帮助开发者快速掌握AXI接口的串口通信技术,提升嵌入式系统开发效率。

weixin_29189377的博客 227

Python模块整理(三):子进程模块subprocess

本来收集整理网络上相关资料后整理: 从python2.4版本开始,可以用subprocess这个模块来产生子进程,并连接到子进程的标准输入/输出/错误中去,还可以得到子进程的返回值。 subprocess意在替代其他几个老的模块或者函数,比如:os.system os.spawn* os.popen* popen2.* commands.* 一、subprocess...

weixin_34320159的博客 8515

IEEE69节点数据(Matlab)

IEEE69节点数据(Matlab)

weixin_46039719的博客 1162

python子进程模块subprocess详解与应用实例 之三

二、应用实例解析 2.1 subprocess模块的使用 1. subprocess.call subprocess.call([“ls”, “-l”]) 0 subprocess.call(“exit 1”, shell=True) 1 调用系统中cmd命令,显示命令执行的结果: x=subprocess.

funny75的专栏 1253

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

python子进程kerberos_python子进程模块subprocess详解与应用实例 之一

subprocess--子进程管理器一、subprocess 模块简介subprocess最早是在2.4版本中引入的。subprocess模块用来生成子进程,并可以通过管道连接它们的输入/输出/错误,以及获得它们的返回值。它用来代替多个旧模块和函数:os.systemos.spawn*os.popen*popen2.*commands.*关于这个模块可以取代的旧函数可以参见 subprocess-...

weixin_39557373的博客 185

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

python子进程模块subprocess详解与应用实例 之一

subprocess--子进程管理器​ 一、subprocess 模块简介 subprocess最早是在2.4版本中引入的。 subprocess模块用来生成子进程,并可以通过管道连接它们的输入/输出/错误,以及获得它们的返回值。 它用来代替多个旧模块和函数: os.system os.spawn* os.popen* popen2.* commands.* 关于这个模

北雨南萍 4429

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

python子进程模块subprocess详解与应用实例 一

一、subprocess 模块简介 subprocess最早是在2.4版本中引入的。 subprocess模块用来生成子进程,并可以通过管道连接它们的输入/输出/错误,以及获得它们的返回值。 它用来代替多个旧模块和函数: os.system os.spawn* os.popen* popen2.* commands.*关于这个模块可以取代的旧函数可以参见 subprocess-rep

funny75的专栏 1754
上一篇: python子进程模块subprocess详解与应用实例 之一
下一篇: python子进程模块subprocess详解与应用实例 之三
北雨南萍
北雨南萍 领域专家: 操作系统技术领域 领域专家: 操作系统技术领域
博客等级 码龄20年 2665粉丝 453原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北雨南萍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值