本节内容

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. 无符号整型 unsigned int、unsigned long、usigned long long、size_t 比较和格式控制

    位数比较 由于数据的长度和平台相关,所以基于 64 位系统比较. Windows Linux unsigned int 32 bits/4294967295 32 bits unsigned long ...

  2. MySQL基础~~编程语法

    常量 数值 字符串:单引号或者双引号括起来.包括普通字符串或者日期格式的字符串. 布尔值:false(FALSE)对应数字值为0.true(TRUE)对应数字值为1. NULL:可以参考http:// ...

  3. MySQL: Connection Refused,调整 mysql.ini中的 max_connections

    连接相同的结构的MySQL数据库,一套库Tomcat启动正常,另一套库一直报Connection Refused. 可以断定是连接数太小了.查找mysql.ini中的 max_connections, ...

  4. Linux命令博客目录

    Linux 目录结构 Linux命令(一) pwd ,cd Linux命令(二) 复制文件 cp Linux命令(三) 移动文件 mv Linux命令(四)删除文件 rm Linux终端常用快捷键 L ...

  5. CentOS virt-manager 安装Win2008r2的一种GUI方法

    1. 必须在物理机上面安装CentOS机器. 安装方法上一个blog里面简单写过. 注意一点,重复安装时 总是提示no disk found 我的解决办法使用 windows 安装盘 格式化了下磁盘重 ...

  6. 电梯间的谈话:3分钟快速回答CEO的问题

    想象一下,你在电梯里遇见了公司的CEO,他让你用3分钟来解释聚焦答案模式这个深奥的术语到底是什么意思.你可以这么说—— 为奠定一个正确的基调,让他酝酿好情绪听你说接下来的话,你可以这样开头: “总裁, ...

  7. Java之Date Time API (Java 8 新特性)

    Java 8 – Date Time API Java 8 comes with a much improved and much required change in the way date an ...

  8. CenOS_6.6_简单搭建vsFTP

    0. 关闭selinux 永久性关闭(这样需要重启服务器后生效) sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config ...

  9. Swagger2 配置

    1. 每个请求都需要换取key: @Bean public Docket createRestApi() { //添加head参数start ParameterBuilder appId = new ...

  10. docker --Dockerfile--一些语法

    环境更换 环境变量(与声明的ENV声明),也可以在特定指令作为变量用来被解释 Dockerfile.转义也被处理,从字面上包含类似于变量的语法. 环境变量Dockerfile用 $variable_n ...