Python subprocess模块常见用法分析

 更新时间:2018年06月12日 08:40:51   作者:breezey  
这篇文章主要介绍了Python subprocess模块常见用法,结合实例形式分析了subprocess模块进程操作相关使用技巧与注意事项,需要的朋友可以参考下

本文实例讲述了Python subprocess模块常见用法。分享给大家供大家参考,具体如下:

subprocess模块是python从2.4版本开始引入的模块。主要用来取代 一些旧的模块方法,如os.system、os.spawn*、os.popen*、commands.*等。subprocess通过子进程来执行外部指令,并通过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,直接抛出异常。需要说明的是,该方法在python3.x中才有。

subprocess.Popen()

在一些复杂场景中,我们需要将一个进程的执行输出作为另一个进程的输入。在另一些场景中,我们需要先进入到某个输入环境,然后再执行一系列的指令等。这个时候我们就需要使用到suprocess的Popen()方法。该方法有以下参数:

args:shell命令,可以是字符串,或者序列类型,如list,tuple。
bufsize:缓冲区大小,可不用关心
stdin,stdout,stderr:分别表示程序的标准输入,标准输出及标准错误
shell:与上面方法中用法相同
cwd:用于设置子进程的当前目录
env:用于指定子进程的环境变量。如果env=None,则默认从父进程继承环境变量
universal_newlines:不同系统的的换行符不同,当该参数设定为true时,则表示使用\n作为换行符

示例1,在/root下创建一个suprocesstest的目录:

>>> 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连接telnet和ssh的两种方式

    详解python连接telnet和ssh的两种方式

    本文主要介绍了python连接telnet和ssh的两种方式,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-10-10
  • python 类的继承 实例方法.静态方法.类方法的代码解析

    python 类的继承 实例方法.静态方法.类方法的代码解析

    这篇文章主要介绍了python 类的继承 实例方法.静态方法.类方法的代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • 基于PyQt5制作一个windows通知管理器

    基于PyQt5制作一个windows通知管理器

    python框架win10toast可以用来做windows的消息通知功能,通过设定通知的间隔时间来实现一些事件通知的功能。本文将利用win10toast这一框架制作一个windows通知管理器,感兴趣的可以参考一下
    2022-02-02
  • python代码中的缩进规则详细解释(史上最全)

    python代码中的缩进规则详细解释(史上最全)

    这篇文章主要介绍了代码缩进的重要性以及在Python语言中的具体规则,代码缩进有助于提高代码的可读性和整洁性,并且是Python语言中一个强制性的语法要求,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2025-01-01
  • Python自动化办公实战案例详解(Word、Excel、Pdf、Email邮件)

    Python自动化办公实战案例详解(Word、Excel、Pdf、Email邮件)

    这篇文章基于Python自动化办公,主要介绍了使用Python相关库,依次完成Word文档替换、Excel表格读取、Pdf文件生成和Email自动邮件发送任务。感兴趣的小伙伴可以跟随小编一起学习一下
    2021-12-12
  • Python内置数据类型详解

    Python内置数据类型详解

    这篇文章主要介绍了Python内置数据类型,需要的朋友可以参考下
    2014-08-08
  • Python3爬虫里关于Splash负载均衡配置详解

    Python3爬虫里关于Splash负载均衡配置详解

    在本篇文章里小编给大家分享了关于Python3爬虫里关于Splash负载均衡配置的相关内容,需要的朋友们可以学习参考下。
    2020-07-07
  • 提升Python程序运行效率的6个方法

    提升Python程序运行效率的6个方法

    这篇文章主要介绍了提升Python程序运行效率的6个方法,包括依赖外部扩展、代码优化等内容,需要的朋友可以参考下
    2015-03-03
  • python 实现一个贴吧图片爬虫的示例

    python 实现一个贴吧图片爬虫的示例

    下面小编就为大家带来一篇python 实现一个贴吧图片爬虫的示例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • Django之模型层多表操作的实现

    Django之模型层多表操作的实现

    这篇文章主要介绍了Django之模型层多表操作的实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-01-01

最新评论