历史

#输出结果到屏幕上,并不返回执行状态
os.system('dir')
#保存命令的执行结果输出
ret = os.popen('dir').read()

问题:上面2条是把命令结果保存下来了,但是返回状态没了,也就没办法判断该命令是否执行成功。例如:

解决方式: 既想要执行结果邮箱要执行状态请使用subprocess模块。

注意:
在python2.7里有个commands模块,可以通过commands.getstatusoutput("dir")查看系统命令的执行状态,但是在3.5里就已经弃用了。
在3.5里新出了一个subprocess模块来替换os.system、os.spawn*、 commands等模块的功能。

subprocess模块:

作用:

1、只获取系统的状态码;
2、只获取shell命令执行后的内容;
3、可以通过Popen来设置一个路径来增删改查文件的操作;
4、可以通过交互式的方式来添加和写入内容操作;
 
 
在python3.5以后的版本可以使用run,之前版本没有run方法:
 #python解析shell命令:
subprocess.run(["df","-h"]) #不用python解析shell命令:(shell=True)
subprocess.run("df -h |grep sda1",shell=True)

一、执行命令,返回状态值,不返回结果:(call)

 1、列表形式(shell = False)
ret = subprocess.call(["ls","-l"],shell=False)
print(ret) 2、字符串形式(shell=True)
ret = subprocess.call("ls -l",shell=True)
print(ret)

二、执行命令,如果状态码是0,则返回0,否则报异常,不反悔结果:(check_call)

 1、列表形式(shell = False)
ret = subprocess.check_call(["ls","-l"],shell=False)
print(ret) 2、字符串形式(shell=True)
ret = subprocess.check_call("ls -l",shell=True)
print(ret)

三、执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常:(check_output)

 1、列表形式(shell = False)
ret = subprocess.check_output(["echo","hello world"],shell=False)
print(ret) 2、字符串形式(shell=True)
ret = subprocess.check_output("exit 1",shell=True)
print(ret)

四、本地创建目录:

使用subprocess.Popen(...) 用于执行复杂的系统命令(上面的方法在后台实际就是调用的Popen)

(一)、参数:
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()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等 。

(二)、输入即可得到输出,如:ifconfig

 import subprocess
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)

五、跳转到指定目录然后在创建目录:

输入进行某环境,依赖再输入,如:python

obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)

六、通过管道进入交互方式:

 import subprocess

 #下面的stdin,stdout,stderr相当于三个管道,以后要想写内容的时候通过管道就可以写。
obj = subprocess.Popen(["python"], #写了一个python,就会进入python解释器,obj就相当于定义一个对象。
stdin=subprocess.PIPE, #专门写的管道1
stdout=subprocess.PIPE, #那正常结果的管道2
stderr=subprocess.PIPE, #用来拿错误的管道3
universal_newlines=True) #向管道里面写数据,下面2个print就相当于写了2行数据。(相当于在终端把命令输入进去了,剩下的就是拿结果)
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)")
obj.stdin.close() #表示停止写入 #可以到stdout的管道中取结果,读到正常输出的结果值
cmd_out = obj.stdout.read()
obj.stdout.close() #如果出现错误,可以到stderr中提取报错结果
cmd_error = obj.stderr.read()
obj.stderr.close() #最后输出执行命令结果
print(cmd_out)
print(cmd_error)

七、合并stdout和stderr的输入结果值:(communicate):

 import subprocess

 obj = subprocess.Popen(["python"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)") out_error_list = obj.communicate() #其实这个命令就是去stdout和stderr两个管道里去拿返回out和error值,不用再次编辑。
print(out_error_list)

八、执行简单的命令:

 import subprocess
obj = subprocess.Popen(["python"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
out_error_list = obj.communicate('print("hello")')
print(out_error_list)

模块讲解----subprocess模块的更多相关文章

  1. python重要模块之subprocess模块

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

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

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

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

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

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

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

  5. python-re模块和subprocess模块

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

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

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

  7. re模块与subprocess模块介绍

    一:re模块       处理正则表达式的模块,正则表达式就是一些带有特殊含义的符号或者符号的组合. 作用:对字符串进行过滤,在一堆字符串中找到你所关心的内容,你就需要告诉计算机你的过滤的 规则是什么 ...

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

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

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

    一.shelve模块 import shelve # 基于pickle模块, d = shelve.open('shelve_test') class Test(object): def __init ...

随机推荐

  1. mysql在命令行中,指定要连接的数据库?

    需求描述: mysql客户端,可以在登录到mysql数据库时,指定要连接到哪个数据库 这里进行一个测试. 测试过程: 1.mysql通过-D参数指定连接到test数据库 [mysql@redhat6 ...

  2. 合格前端系列第六弹-从指向看JavaScript

    https://my.oschina.net/qiangdada/blog/1484001

  3. oracle的常用函数 instr() 和substr()函数

    from:http://1055592535.iteye.com/blog/1676235 在Oracle中 可以使用instr函数对某个字符串进行判断,判断其是否含有指定的字符. 在一个字符串中查找 ...

  4. VS------修改项目命名空间

    1.以文本形式打开此文件 2.修改一下部分 3.vs会自动提示,选择“放弃”即可

  5. eclipse导入maven项目时报Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources

    在用Eclipse IDE for Java EE Developers进行maven项目的开发时,报错Could not calculate build plan: Plugin org.apach ...

  6. Html5 拖拽行为和AngularJs的结合

    一. Html5的拖拽行为 1.设置元素为可拖放:把draggable属性设置为true. example: <div id="drag1" draggable=" ...

  7. Bettercap的安装和使用嗅探WIFI

    一.首先安装bettercap 我这里的环境是ubuntu 16.04 apt-get install build-essential ruby-dev libpcap-dev git ruby ge ...

  8. android通过数组,流播放声音的方法,音频实时传输

    AudioRecord和AudioTrack类是Android获取和播放音频流的重要类,放置在android.media包中.与该包中 的MediaRecorder和MediaPlayer类不同,Au ...

  9. 解决Activity启动黑屏及设置android:windowIsTranslucent不兼容activity切换动画问题

    From:http://blog.csdn.net/fancylovejava/article/details/39643449 之前在做 APP 的时候不太关注这个问题,因为自己在使用其他 APP ...

  10. Android 动态设置控件高度

    TextView textView= (TextView)findViewById(R.id.textview); LinearLayout.LayoutParams linearParams =(L ...