本节内容

1、概述

2、前言

3、subprocess模块

4、subprocess.Popen()

一、概述

  我们在实际的工作中,需要跟操作系统的命令做交互,但我们如何用python去跟操作系统之间做交互呢?下面就来说说我们今天需要学习的模块:subprocess。

二、前言

  在没有subprocess这个模块的时候,我们怎么去跟我们的操作系统做交互的呐?下面我们先说说这三个模块:os.system()、os.popen()、commands。

1、os.system()

作用:执行操作系统命令,只返回命令的执行状态(0:成功,非0:失败),不返回命令的执行结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> import os
>>> os.system("ls -l")
total 16708
-rw-------1 root root     1350 Jan  4 01:51 anaconda-ks.cfg
-rw-r--r--1 root root     8017 Jan  4 01:51 install.log
0  #执行返回的状态
>>> res = os.system("ls -l")
total 16708
-rw-------1 root root     1350 Jan  4 01:51 anaconda-ks.cfg
-rw-r--r--1 root root     8017 Jan  4 01:51 install.log
>>> res
0   #0: 表示成功
>>> res = os.system("lm")
sh: lm: command not found
>>> res
32512  #非0:表示失败

2、os.popen()

作用:执行操作系统命令,不返回命令的执行状态,只返回命令的执行结果。

1
2
3
4
5
6
7
8
9
>>> import os
>>> os.popen("ls -l")
<open file 'ls -l', mode 'r' at 0x7f5ded070540>
>>> res = os.popen("ls -l")
>>> a = res.read()
>>> print(a)  #打印返回结果
total 16708
-rw-------1 root root     1350 Jan  4 01:51 anaconda-ks.cfg
-rw-r--r--1 root root     8017 Jan  4 01:51 install.log

注:执行popen()不是直接返回命令的执行结果的,而是需要read一下,这是因为popen相当于打开了一个文件,它把结果存到文件中,只不过它是相当于存在内存中了,但是你好像打开文件的样子去取一样。

3、commands模块

作用:既可以获取命令的执行状态,也可以获取命令的执行结果,但是只能在python2.7有这个命令,在python3.5之后就没有,还有就是这个模块功能只支持Linux,Windows不支持,这边知道这个命令就行了,先忘记它吧。

1
2
3
4
5
6
7
8
9
10
11
>>> import commands  #导入commands命令
>>> commands.getstatusoutput("ls -l")
(0, 'total 16708\n-rw-------1 root root     1350 Jan  4 01:51 anaconda-ks.cfg\n
-rw-r--r--1 root root     8017 Jan  4 01:51 install.log') #元组的形式返回
>>> res = commands.getstatusoutput("ls -l")
>>> res[0]  #执行状态
0
>>> print(res[1])  #执行结果
total 16708
-rw-------1 root root     1350 Jan  4 01:51 anaconda-ks.cfg
-rw-r--r--1 root root     8017 Jan  4 01:51 install.log

三、subprocess模块

  上面说commands模块在python3.5以后的版本就没有了,而且它又不支持Windows,那怎么办呢?不用担心,python3.5之后又出来新的模块更为强大,subprocess模块,下面我们就来说说它是运作的。

1、subprocess.run()

作用:运行命令,返回命令执行的结果(python3.5以后的版本才会有这个命令)

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> 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)

注:看到上面run函数的使用,这边有很多小伙伴有点不解,这边我解释一下:第1种情况是:执行的命令需要让python去解释执行这个命令,执行的命令以及参数,需要以列表的形式传入。第二种情况:但是如果需要交给Linux shell环境去解析的还,这传入命令的字符串,并且声明shell=True即可。

2、subprocess.call()

作用:执行命令,返回命令的状态,0或者非0

1
2
3
4
5
6
7
8
>>> import subprocess
>>> res = subprocess.call(["ls","-l"])
total 26976
-rw-r--r--  1 1000 1000    10914 Jan 17 15:57 aclocal.m4
drwxr-xr-x  5 root root     4096 May 12 14:21 build
-rwxr-xr-x  1 1000 1000    43940 Jan 17 15:57 config.guess
>>> res  #返回命令的状态
0

3、subprocess.check_call()

作用:执行命令,如果执行结果为0,正常返回,否则抛异常

1
2
3
4
5
6
7
>>> import subprocess
>>> res = subprocess.check_call(["ls","-l"])
total 26976
-rw-r--r--  1 1000 1000    10914 Jan 17 15:57 aclocal.m4
drwxr-xr-x  5 root root     4096 May 12 14:21 build
>>> res
0

4、subprocess.getstatusoutput()

作用:接收字符串形式的命令,返回元组形式,第1个元素是执行状态,第二个是命令结果

1
2
3
>>> import subprocess
>>> subprocess.getstatusoutput('ls /bin/ls')
(0'/bin/ls'#0:执行状态,'bin/ls':执行结果

5、subprocess.getoutput()

作用:接收字符串形式的命令,并且返回命令的结果

1
2
3
>>> import subprocess
>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls'   #返回命令的结果

6、subprocess.check_output()

作用:执行命令,并且返回结果,不是打印

1
2
3
4
5
6
7
>>> import subprocess
>>> res = subprocess.check_output(["ls","-l"])
>>> res
b'total 26976\n-rw-r--r--  1 1000 1000    10914 Jan 17 15:57 aclocal.m4\n
drwxr-xr-x  5 root root     4096 May 12 14:21 build\n
-rwxr-xr-x  1 1000 1000    43940 Jan 17 15:57 config.guess\n
-rw-r--r--  1 root root   756903 May 12 14:18 config.log\n'   #这边是以字节类型返回的

四、subprocess.Popen()

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

1、stdout

作用:标准输出

1
2
3
4
5
6
7
>>> import subprocess
>>> res = subprocess.Popen("df -h",shell=True,stdout=subprocess.PIPE) #需要管道标准输出
>>> res.stdout.read() #标准输出
b'Filesystem            Size  Used Avail Use% Mounted on\n/dev/mapper/VolGroup-
LogVol00\n                      289G   70G  204G  26% /\ntmpfs                  64G     0   64G
 0% /dev/shm\n/dev/sda1             283M   27M  241M  11% /boot\n'
>>> obj.stdout.close() #关闭标准输出

2、stdin

作用:标准输入

1
2
3
4
5
6
7
8
9
>>> import subprocess
>>> obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)        
>>> obj.stdin.write("hello world")  #标准输入
>>> obj.stdin.close() #关闭标准输入
#这里输入完成了是不是的把他的输出读出来?
>>> cmd_out = obj.stdout.read() #获取启动的进程的标准输出
>>> obj.stdout.close() #关闭标准输出
>>> cmd_error = obj.stderr.read() #获取启动的进程的标准错误
>>> obj.stderr.close() #关闭启动程序的标准错误

3、stderr

作用:标准错误

1
2
3
4
5
>>> import subprocess
>>> res = subprocess.Popen("lm -l",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)  
>>> res.stderr.read()  #标准输出错误
'/bin/sh: lm: command not found\n'
>>> obj.stderr.close() #关闭启动程序的标准错误

注意:上面的提到的标准输出都为啥都需要等于subprocess.PIPE,这个又是啥呢?原来这个是一个管道,这个需要画一个图来解释一下:

4、poll()

作用:定时检查命令有没有执行完毕,执行完毕返回0,没有完毕返回None

1
2
3
4
5
6
>>> import subprocess
>>> res = subprocess.Popen("sleep 20;echo 'hello'",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> print(res.poll()) 
None   #没有执行完毕
>>> print(res.poll())
0   #执行完毕

5、wait()

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

1
2
3
4
5
6
>>> res = subprocess.Popen("sleep 20;echo 'hello'",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> res.wait()
############
漫长等待中
############
0  #等待结束,返回执行结果状态

6、terminate()

作用:杀掉启动进程

1
2
3
4
5
>>> import subprocess
>>> res = subprocess.Popen("sleep 20;echo 'hello'",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> res.terminate()  #杀掉启动的进程
>>> res.stdout.read()  #杀掉后,标准输出为空
b''

7、communicate()

作用:执行的过程传数据,没什么用,先忘记它吧!以后用到再说

1
2
3
4
5
6
>>> import subprocess
>>> obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)        
>>> obj.stdin.write("hello world")  #标准输入
>>> out_error_list = obj.communicate(timeout=10)
>>> print(out_error_list)  #输入的结果
('', '  File "<stdin>", line 1\n    hello world\n              ^\nSyntaxError: invalid syntax\n')

8、pid

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

1
2
3
4
>>> import subprocess
>>> res = subprocess.Popen("sleep 20;echo 'hello'",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
>>> res.pid  #获取这个Linux shell的环境的进程号
30225

9、可用参数

  1. args:shell命令,可以是字符串或者序列类型(如:list,元组)
  2. bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
  3. stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
  4. preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
  5. close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
  6. shell:同上
  7. cwd:用于设置子进程的当前目录
  8. env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
  9. universal_newlines:不同系统的换行符不同,True -> 同意使用 \n
  10. startupinfo与createionflags只在windows下有效将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等

函数和常用模块【day06】:subprocess模块(十)的更多相关文章

  1. python重要模块之subprocess模块

    python重要模块之subprocess模块 我们经常要通过python去执行系统的命令或者脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就相当于发起了一个新的进程, ...

  2. logging模块、shutil模块、subprocess模块、xml模块

    logging模块 shutil模块 subprocess模块 xml模块 logging模块 函数式简单配置 import logging logging.debug('debug message' ...

  3. configparser模块,subprocess 模块,xlrd,xlwt ,xml 模块,面向对象

    1. configparser模块 2.subprocess 模块 3.xlrd,xlwt 4.xml 模块 5.面向对象 面向对象是什么? 是一种编程思想,指导你如何更好的编写代码 关注点在对象 具 ...

  4. [xml模块、hashlib模块、subprocess模块、os与sys模块、configparser模块]

    [xml模块.hashlib模块.subprocess模块.os与sys模块.configparser模块] xml模块 XML:全称 可扩展标记语言,为了能够在不同的平台间继续数据的交换,使交换的数 ...

  5. os模块、os.path模块、shutil模块、configparser模块、subprocess模块

    一.os模块 os指的是操作系统 该模块主要用于处理与操作系统相关的操作,常用的是文件操作(读.写.删.复制.重命名). os.getcwd()  获取当前文件所在的文件夹路径 os.chdir()  ...

  6. os模块,sys模块,json模块,subprocess模块

    os模块 一·什么是os模块 os模块提供了多数操作系统的功能接口函数.当os模块被导入后,它会自适应于不同的操作系统平台,根据不同 的平台进行相应的操作,在python编程时,经常和文件.目录打交道 ...

  7. python-re模块和subprocess模块

    一.re模块 re中文为正则表达式,是字符串处理的常用工具,通常用来检索和替换符合某个模式的文本. 注:要搜索的模式和字符串都可以是unicode字符串(str)和8位字符串(bytes),但是不能将 ...

  8. 模块讲解----subprocess模块

    历史 #输出结果到屏幕上,并不返回执行状态os.system('dir')#保存命令的执行结果输出ret = os.popen('dir').read() 问题:上面2条是把命令结果保存下来了,但是返 ...

  9. Python开发基础-Day15正则表达式爬虫应用,configparser模块和subprocess模块

    正则表达式爬虫应用(校花网) import requests import re import json #定义函数返回网页的字符串信息 def getPage_str(url): page_stri ...

  10. python基础之正则表达式爬虫应用,configparser模块和subprocess模块

    正则表达式爬虫应用(校花网) 1 import requests 2 import re 3 import json 4 #定义函数返回网页的字符串信息 5 def getPage_str(url): ...

随机推荐

  1. [cnbeta]华为值多少钱,全世界非上市公司中估值最高的巨头

    华为值多少钱,全世界非上市公司中估值最高的巨头 https://www.cnbeta.com/articles/tech/808203.htm   小米.美团都曾表达过不想.不急于上市,但没人信,所以 ...

  2. Windows查看端口被什么进程占用的简单方法----菜鸟养成

    1.  还是因为同事告知Oracle的服务器连不上 最后发现改了端口就可以了, 但是很困惑 不知道为什么会这样,然后简单查了下: 命令 netstat -ano 查看监听的端口 baidu出来一个管道 ...

  3. [转帖]git命令参考手册

                      git init                                                  # 初始化本地git仓库(创建新仓库) git ...

  4. SAP PA认证

    ----------------------------------------------------------------转帖---------------------------------- ...

  5. 设计模式之工厂模式(c++)

    问题描述 在面向对象系统设计中经常可以遇到以下的两类问题:1)为了提高内聚(Cohesion)和松耦合(Coupling),我们经常会抽象出一些类的公共接口以形成抽象基类或者接口.这样我们可以通过声明 ...

  6. matplotlib绘图pie

    #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/5/28 16:05 # @Author : zhang chao # @Fi ...

  7. 关于utf8mb4的学习了解笔记

    占位下班写 据说可以存储emoji ..妈蛋今天大神又秀我一脸 大概意思是,我们整个后端数据库,最近都升级了编码格式.从以前久的utf-8整个升级到了utf8mb4的格式 该格式支持emoji表情. ...

  8. iptables防火墙配置

    iptables防火墙配置 一.防火墙简介 1.功能: 1)通过源端口,源IP地址,源MAC地址,包中特定标记和目标端口,IP,MAC来确定数据包是否可以通过防火墙 2)分割内网和外网[附带的路由器的 ...

  9. Python 零基础 快速入门 趣味教程 (咪博士 海龟绘图 turtle) 5. 参数

    上一个教程中,咪博士带大家学习了函数的使用.例如,line_without_moving 函数,可以让海龟先画出一条线段,然后再回来起点. def line_without_moving(): tur ...

  10. python之unittest单元测试

    # unittest单元测试 import unittest from class_demo import Car class TestCar(unittest.TestCase): '''测试Car ...