Python subprocess模块常见用法分析

拾柒
拾柒
发布时间:2026-10-13| 8人浏览过
原创

本文详细解析Python 2.4引入的subprocess模块,涵盖call、check_call、check_output及Popen等核心方法。重点演示如何通过stdin/stdout/stderr管道实现进程间数据传递,包括命令执行、参数配置及复杂场景下的进程控制与通信技巧。

本文详细介绍Python中subprocess模块的常见应用场景与用法,供读者参考学习。

subprocess模块自Python 2.4版本起被引入,旨在替代os.system、os.spawn*、os.popen*及commands.*等旧有模块方法。该模块通过创建子进程来执行外部指令,并利用input、output和error管道获取子进程执行后的返回信息。

以下是该模块中常用的几种方法:

subprocess.call():用于执行命令并返回执行状态码。当shell参数设为False时,命令需以列表形式传入;若shell为True,则可直接传入字符串形式的命令。

具体示例如下:

>>> a = subprocess.call(['df','-hT'],shell=False)
Filesystem Type Size Used Avail Use% Mounted on
/dev/sda2  ext4  94G 64G 26G 72% /
tmpfs  tmpfs 2.8G  0 2.8G 0% /dev/shm
/dev/sda1  ext4 976M 56M 853M 7% /boot
>>> a = subprocess.call('df -hT',shell=True)
Filesystem Type Size Used Avail Use% Mounted on
/dev/sda2  ext4  94G 64G 26G 72% /
tmpfs  tmpfs 2.8G  0 2.8G 0% /dev/shm
/dev/sda1  ext4 976M 56M 853M 7% /boot
>>> print a
0

subprocess.check_call():其用法与subprocess.call()类似,主要区别在于,当子进程返回值不为0时,该方法会直接抛出异常。

示例代码:

>>> a = subprocess.check_call('df -hT',shell=True)
Filesystem Type Size Used Avail Use% Mounted on
/dev/sda2  ext4  94G 64G 26G 72% /
tmpfs  tmpfs 2.8G  0 2.8G 0% /dev/shm
/dev/sda1  ext4 976M 56M 853M 7% /boot
>>> print a
0
>>> a = subprocess.check_call('dfdsf',shell=True)
/bin/sh: dfdsf: command not found
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/usr/lib64/python2.6/subprocess.py", line 502, in check_call
 raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'dfdsf' returned non-zero exit status 127

subprocess.check_output():用法与前两者相似,但行为有所不同:若返回值为0,则直接返回输出结果;若返回值不为0,则直接抛出异常。需要注意的是,该方法仅在Python 3.x版本中存在。

subprocess.Popen():

在复杂场景中,常需将一个进程的执行输出作为另一个进程的输入;或需先进入特定输入环境再执行一系列指令。此时应使用subprocess的Popen()方法。该方法包含以下参数:

args:Shell命令,可为字符串或序列类型(如list、tuple)。 bufsize:缓冲区大小,通常无需特别关注。 stdin, stdout, stderr:分别表示程序的标准输入、标准输出及标准错误流。 shell:用法与前述方法一致。 cwd:用于设置子进程的当前工作目录。 env:用于指定子进程的环境变量;若env为None,则默认继承父进程的环境变量。 universal_newlines:因不同系统换行符不同,当该参数设为True时,统一使用\n作为换行符。

示例1:在/root目录下创建一个名为subprocesstest的目录:

>>> a = subprocess.Popen('mkdir subprocesstest',shell=True,cwd='/root')

示例2:使用Python执行多条命令:

import subprocess
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n')
obj.stdin.write('print 2 \n')
obj.stdin.write('print 3 \n')
obj.stdin.write('print 4 \n')
obj.stdin.close()
cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error = obj.stderr.read()
obj.stderr.close()
print cmd_out
print cmd_error

也可采用以下替代方法:

import subprocess
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n')
obj.stdin.write('print 2 \n')
obj.stdin.write('print 3 \n')
obj.stdin.write('print 4 \n')
out_error_list = obj.communicate()
print out_error_list

示例3:将一个子进程的输出作为另一个子进程的输入:

import subprocess
child1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE)
child2 = subprocess.Popen(["grep","0:0"],stdin=child1.stdout, stdout=subprocess.PIPE)
out = child2.communicate()

其他辅助方法:

import subprocess
child = subprocess.Popen('sleep 60',shell=True,stdout=subprocess.PIPE)
child.poll() #检查子进程状态
child.kill()  #终止子进程
child.send_signal() #向子进程发送信号
child.terminate() #终止子进程

如需了解更多Python相关内容,可参考本站专题:《Python进程与线程操作技巧总结》、《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》。

希望本文所述内容能对大家的Python程序设计有所帮助。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。