subprocess模块使用

subprocess 模块

一、简介

subprocess最早在2.4版本引入。用来生成子进程,并可以通过管道连接他们的输入/输出/错误,以及获得他们的返回值。

subprocess用来替换多个旧模块和函数:

os.system
os.spawn*
os.popen*
popen2.*
commands.*
运行python的时候,我们都是在创建并运行一个进程,linux中一个进程可以fork一个子进程,并让这个子进程exec另外一个程序。在python中,我们通过标准库中的subprocess包来fork一个子进程,并且运行一个外部的程序。subprocess包中定义有数个创建子进程的函数,这些函数分别以不同的方式创建子进程,所欲我们可以根据需要来从中选取一个使用。另外subprocess还提供了一些管理标准流(standard stream)和管道(pipe)的工具,从而在进程间使用文本通信。

二、旧模块的使用

1.os.system()

执行操作系统的命令,将结果输出到屏幕,只返回命令执行状态(0:成功,非 0 : 失败)

import os

>>> a = os.system("df -Th")
Filesystem Type Size Used Avail Use% Mounted on
/dev/sda3 ext4 1.8T 436G 1.3T 26% /
tmpfs tmpfs 16G 0 16G 0% /dev/shm
/dev/sda1 ext4 190M 118M 63M 66% /boot

>>> a
0 # 0 表示执行成功

# 执行错误的命令
>>> res = os.system("list")
sh: list: command not found
>>> res
32512 # 返回非 0 表示执行错误
  

2. os.popen()

执行操作系统的命令,会将结果保存在内存当中,可以用read()方法读取出来

import os

>>> res = os.popen("ls -l")

# 将结果保存到内存中
>>> print res
<open file ‘ls -l‘, mode ‘r‘ at 0x7f02d249c390>

# 用read()读取内容
>>> print res.read()
total 267508
-rw-r--r-- 1 root root 260968 Jan 27 2016 AliIM.exe
-rw-------. 1 root root 1047 May 23 2016 anaconda-ks.cfg
-rw-r--r-- 1 root root 9130958 Nov 18 2015 apache-tomcat-8.0.28.tar.gz
-rw-r--r-- 1 root root 0 Oct 31 2016 badblocks.log
drwxr-xr-x 5 root root 4096 Jul 27 2016 certs-build
drwxr-xr-x 2 root root 4096 Jul 5 16:54 Desktop
-rw-r--r-- 1 root root 2462 Apr 20 11:50 Face_24px.ico
  

三、subprocess模块

1、subprocess.run()

>>> import subprocess
# python 解析则传入命令的每个参数的列表
>>> subprocess.run(["df","-h"])
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-LogVol00
289G 70G 204G 26% /
tmpfs 64G 0 64G 0% /dev/shm
/dev/sda1 283M 27M 241M 11% /boot
CompletedProcess(args=[‘df‘, ‘-h‘], returncode=0)

# 需要交给Linux shell自己解析,则:传入命令字符串,shell=True
>>> subprocess.run("df -h|grep /dev/sda1",shell=True)
/dev/sda1 283M 27M 241M 11% /boot
CompletedProcess(args=‘df -h|grep /dev/sda1‘, returncode=0)
  

2、subprocess.call()

执行命令,返回命令的结果和执行状态,0或者非0

>>> res = subprocess.call(["ls","-l"])
总用量 28
-rw-r--r-- 1 root root 0 6月 16 10:28 1
drwxr-xr-x 2 root root 4096 6月 22 17:48 _1748
-rw-------. 1 root root 1264 4月 28 20:51 anaconda-ks.cfg
drwxr-xr-x 2 root root 4096 5月 25 14:45 monitor
-rw-r--r-- 1 root root 13160 5月 9 13:36 npm-debug.log

# 命令执行状态
>>> res
0
  

3、subprocess.check_call()

执行命令,返回结果和状态,正常为0 ,执行错误则抛出异常

>>> subprocess.check_call(["ls","-l"])
总用量 28
-rw-r--r-- 1 root root 0 6月 16 10:28 1
drwxr-xr-x 2 root root 4096 6月 22 17:48 _1748
-rw-------. 1 root root 1264 4月 28 20:51 anaconda-ks.cfg
drwxr-xr-x 2 root root 4096 5月 25 14:45 monitor
-rw-r--r-- 1 root root 13160 5月 9 13:36 npm-debug.log
0

>>> subprocess.check_call(["lm","-l"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/subprocess.py", line 537, in check_call
retcode = call(*popenargs, **kwargs)
File "/usr/lib64/python2.7/subprocess.py", line 524, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
  

4、subprocess.getstatusoutput()

接受字符串形式的命令,返回 一个元组形式的结果,第一个元素是命令执行状态,第二个为执行结果

#执行正确
>>> subprocess.getstatusoutput(‘pwd‘)
(0, ‘/root‘)

#执行错误
>>> subprocess.getstatusoutput(‘pd‘)
(127, ‘/bin/sh: pd: command not found‘)
  

5、subprocess.getoutput()

接受字符串形式的命令,放回执行结果

>>> subprocess.getoutput(‘pwd‘)
‘/root‘
  

6、subprocess.check_output()

执行命令,返回执行的结果,而不是打印

>>> res = subprocess.check_output("pwd")
>>> res
b‘/root\n‘ # 结果以字节形式返回
  

四、subprocess.Popen()

其实以上subprocess使用的方法,都是对subprocess.Popen的封装,下面我们就来看看这个Popen方法。

1、stdout

标准输出

>>> res = subprocess.Popen("ls /tmp/yum.log", shell=True, stdout=subprocess.PIPE) # 使用管道
>>> res.stdout.read() # 标准输出
b‘/tmp/yum.log\n‘

res.stdout.close() # 关闭

  

2、stderr

标准错误

>>> import subprocess
>>> res = subprocess.Popen("lm -l",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# 标准输出为空
>>> res.stdout.read()
b‘‘

#标准错误中有错误信息
>>> res.stderr.read()
b‘/bin/sh: lm: command not found\n‘

3、poll()

定时检查命令有没有执行完毕,执行完毕后返回执行结果的状态,没有执行完毕返回None

>>> res = subprocess.Popen("sleep 10;echo ‘hello‘",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> print(res.poll())
None
>>> print(res.poll())
None
>>> print(res.poll())
0
  

4、wait()

等待命令执行完成,并且返回结果状态

>>> obj = subprocess.Popen("sleep 10;echo ‘hello‘",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> obj.wait()

# 中间会一直等待

0
  
5、terminate()

结束进程

import subprocess

>>> res = subprocess.Popen("sleep 20;echo ‘hello‘",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> res.terminate() # 结束进程
>>> res.stdout.read()
b‘‘
  

6、pid

获取当前执行子shell的程序的进程号

import subprocess

>>> res = subprocess.Popen("sleep 5;echo ‘hello‘",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> res.pid # 获取这个linux shell 的 进程号
2778

时间: 2024-07-31 23:51:46

subprocess模块使用的相关文章

Python中subprocess 模块 创建并运行一个进程

python的subprocess模块,看到官方声明里说要尽力避免使用shell=True这个参数,于是测试了一下: from subprocess import call import shlex cmd = "cat test.txt; rm test.txt" call(cmd, shell=True) 运行之后: 1:打开并浏览了test.txt文件 2:删除了test.txt文件 from subprocess import call import shlex cmd = &

python subprocess模块

转 http://blog.csdn.net/imzoer/article/details/8678029 subprocess的目的就是启动一个新的进程并且与之通信. subprocess模块中只定义了一个类: Popen.可以使用Popen来创建进程,并与进程进行复杂的交互.它的构造函数如下: subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=

[ python编程 ] subprocess模块学习总结

转载:http://www.jb51.net/article/48086.htm 从Python 2.4开始,Python引入subprocess模块来管理子进程,以取代一些旧模块的方法:如 os.system.os.spawn*.os.popen*.popen2.*.commands.*不但可以调用外部的命令作为子进程,而且可以连接到子进程的input/output/error管道,获取相关的返回信息. 一.subprocess以及常用的封装函数    运行python的时候,我们都是在创建并

subprocess模块

subprocess模块 subprocess的目的就是启动一个新的进程并且与之通信. subprocess模块中只定义了一个类: Popen.可以使用Popen来创建进程,并与进程进行复杂的交互. subprocess.Popen(...) 用于执行复杂的系统命令 参数: args:shell命令,可以是字符串或者序列类型(如:list,元组) bufsize:指定缓冲.0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲 stdin, stdout, stderr:分别表示程序的标准输入

s14 第6天 subprocess模块 面向对象

subprocess模块 ret = os.system("command") 输出命令的结果,但是只返回命令的执行状态,因此ret的值在正常返回为0,不正常为非0 ret = os.popen("command").read() 此命令返回命令执行的结果,ret是命令的输出,但是没有执行状态 import   commands ret =   commands.getstatusoutput("command") 在python 2.7中存在,

python16_day06【类、RE模块、subprocess模块、xml模块、shelve模块】

.title { background-color: #000000; color: #00f508 } 一.shelve模块 1 import shelve 2 3 # 基于pickle模块, 4 5 d = shelve.open('shelve_test') 6 7 8 class Test(object): 9 def __init__(self, n): 10 self.n = n 11 12 t1 = Test(123) 13 t2 = Test(456) 14 name = ['a

python学习道路(day7note)(subprocess模块,面向对象)

1.subprocess模块   因为方法较多我就写在code里面了,后面有注释 1 #!/usr/bin/env python 2 #_*_coding:utf-8_*_ 3 4 #linux 上调用python脚本 5 #os.system输出命令结果到屏幕,返回命令执行状态 6 #os.popen("dir") 返回内存对象,需要单独去取一下 7 #os.popen("dir").read() 保存命令的执行结果输出,但是不返回执行状态 8 # 9 10 #p

Python学习笔记——基础篇【第六周】——Subprocess模块

执行系统命令 可以执行shell命令的相关模块和函数有: os.system os.spawn* os.popen*          --废弃 popen2.*           --废弃 commands.*      --废弃,3.x中被移除 1 import commands 2 3 result = commands.getoutput('cmd') 4 result = commands.getstatus('cmd') 5 result = commands.getstatuso

python_day6 subprocess模块,

os.system功能,不直接打印到屏幕,而是传递参数 如果想将结果放入变量再随意打印 就需要 subprocess 模块了 将执行结果丢入管道(正确的进stdout,错误的进stderr, 执行双命令,第二个命令  用stdin);管道的值只能取一次 import subprocesssubprocess.Popen('dir',shell=True) -->直接打印 res=subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE)--

python的subprocess模块

从Python 2.4开始,Python引入subprocess模块来管理子进程,以取代一些旧模块的方法:如 os.system.os.spawn*.os.popen*.popen2.*.commands.*不但可以调用外部的命令作为子进程,而且可以连接到子进程的input/output/error管道,获取相关的返回信息 一.subprocess以及常用的封装函数运行python的时候,我们都是在创建并运行一个进程.像Linux进程那样,一个进程可以fork一个子进程,并让这个子进程exec另