Python模块——subprocess
subprocess模块
通过Python去执行一条系统命令或脚本。
三种执行命令的方法
subprocess.run(*popenargs, input=None, timeout=None, check=False, **kwargs) #官方推荐
subprocess.call(*popenargs, timeout=None, **kwargs) #跟上面实现的内容差不多,另一种写法
subprocess.Popen() #上面各种方法的底层封装
run方法
标准写法
subprocess.run(['df','-h'],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True)
#check=True代表,如果命令出现错误,程序会抛出异常

涉及到管道|的命令需要这样写
subprocess.run('df -h|grep disk1',shell=True) #shell=True的意思是这条命令直接交给系统去执行,不需要python负责解析

call方法
#执行命令,返回命令执行状态 , 0 or 非0
>>> retcode = subprocess.call(["ls", "-l"]) #执行命令,如果命令结果为0,就正常返回,否则抛异常
>>> subprocess.check_call(["ls", "-l"])
0 #接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果
>>> subprocess.getstatusoutput('ls /bin/ls')
(0, '/bin/ls') #接收字符串格式命令,并返回结果
>>> subprocess.getoutput('ls /bin/ls')
'/bin/ls' #执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res
>>> res=subprocess.check_output(['ls','-l'])
>>> res
b'total 0\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n'
Popen方法
常用参数:
- args:shell命令,可以是字符串或者序列类型(如:list,元组)
- stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
- preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
- shell:同上
- cwd:用于设置子进程的当前目录
- env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
下面这2条语句执行会有什么区别?
a=subprocess.run('sleep 10',shell=True,stdout=subprocess.PIPE)
a=subprocess.Popen('sleep 10',shell=True,stdout=subprocess.PIPE)
区别是Popen会在发起命令后立刻返回,而不等命令执行结果。这样的好处是什么呢?
如果你调用的命令或脚本 需要执行10分钟,你的主程序不需卡在这里等10分钟,可以继续往下走,干别的事情,每过一会,通过一个什么方法来检测一下命令是否执行完成就好了。
Popen调用后会返回一个对象,可以通过这个对象拿到命令执行结果或状态等,该对象有以下方法
poll() Check if child process has terminated. Returns returncode wait() Wait for child process to terminate. Returns returncode attribute. terminate()终止所启动的进程Terminate the process with SIGTERM kill() 杀死所启动的进程 Kill the process with SIGKILL
send_signal(signal.xxx)发送系统信号 pid 拿到所启动进程的进程号
poll
>>> a=subprocess.Popen('sleep 10',shell=True,stdout=subprocess.PIPE)
>>> a.poll()
>>> a.poll()
>>> a.poll()
0
termiate
>>> a = subprocess.Popen('for i in $(seq 1 100);do sleep 1;echo $i >> /tmp/sleep.log;done',shell=True, cwd='/tmp',stdout=subprocess.PIPE)
>>> a.terminate()
>>>

preexec_fn
>>> def sayhi():
... print('haha')
...
>>> a = subprocess.Popen('sleep 5',shell=True,stdout=subprocess.PIPE,preexec_fn=sayhi)
>>> a.stdout
<_io.BufferedReader name=3>
>>> a.stdout.read()
b'haha\n'
>>> a.pid
2070
代码案例
import subprocess
from utils import unicode_utils
# 执行cmd或shell命令#
from multiprocessing.dummy import Pool as ThreadPool def cmd_exec(cmd):
"""
执行shell命令
返回命令返回值和结果
:param cmd:
:return:
"""
p = subprocess.Popen(cmd,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE) stdout, stderr = p.communicate()#从PIPE中读取出PIPE中的文本,放入内存
if p.returncode != 0:
return {'code':p.returncode, 'res':unicode_utils.to_str(stderr)}
return {'code':p.returncode, 'res':unicode_utils.to_str(stdout)} if __name__ == '__main__':
pass
cmd_list =[]
cmd_list.append('df -h')
cmd_list.append('ps -ef|grep jav1a|grep -v grep')
cmd_list.append('ps -ef|grep "pol"')
cmd_list.append('sh /root/ops/sum.sh')
# print(cmd_exec(cmd))
# Make the Pool of workers
pool = ThreadPool(4)
# Open the urls in their own threads
# and return the results
results = pool.map(cmd_exec, cmd_list)
# close the pool and wait for the work to finish
print(results)
pool.close()
pool.join() **************************************
unicode_utils: def to_str(bytes_or_str):
"""
把byte类型转换为str
:param bytes_or_str:
:return:
"""
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value
Python模块——subprocess的更多相关文章
- Python基础篇【第6篇】: Python模块subprocess
subprocess Python中可以执行shell命令的相关模块和函数有: os.system os.spawn* os.popen* --废弃 popen2.* ...
- Python模块subprocess小记
转自:http://www.oschina.net/question/234345_52660 熟悉了Qt的QProcess以后,再回头来看python的subprocess总算不觉得像以前那么恐怖了 ...
- 【转】Python模块subprocess
subprocess 早期的Python版本中,我们主要是通过os.system().os.popen().read()等函数.commands模块来执行命令行指令的,从Python 2.4开始官方文 ...
- Python模块subprocess
subprocess的常用用法 """ Description: Author:Nod Date: Record: #-------------------------- ...
- python模块subprocess学习
当我们想要调用系统命令,可以使用os,commands还有subprocess模块整理如下: os模块: 1. os.system 输出命令结果到屏幕.返回命令执行状态. >>> o ...
- Python模块-subprocess模块
Run()方法 >>> a = subprocess.run(['df','-h']) 文件系统 容量 已用 可用 已用% 挂载点 udev 468M 0 468M 0% /dev ...
- python模块之subprocess
可以执行shell命令的相关模块和函数有: os.system os.spawn* os.popen* --废弃 popen2.* --废弃 commands.* ...
- python模块基础之json,requeste,xml,configparser,logging,subprocess,shutil。
1.json模块 json 用于[字符串]和 [python基本数据类型] 间进行转换(可用于不同语言之前转换),json.loads,将字符串转成python的基本数据类型,json.dum ...
- [转载]Python模块学习 ---- subprocess 创建子进程
[转自]http://blog.sciencenet.cn/blog-600900-499638.html 最近,我们老大要我写一个守护者程序,对服务器进程进行守护.如果服务器不幸挂掉了,守护者能即时 ...
随机推荐
- python list中append()方法和extend()方法区别
共同点 只能作用于list类型(不能作用于tuple等其他类型) 单参数限制(不支持多参数) 不同点 list.append(object) 向列表中添加一个对象object. 使用append的时候 ...
- JAVA中float与double的区别
float是单精度类型,精度是8位有效数字,取值范围是10的-38次方到10的38次方,float占用4个字节的存储空间 double是双精度类型,精度是17位有效数字,取值范围是10的-308次方到 ...
- Linq的执行效率及优化
描述:项目中使用了linq,发现写的顺序不一样最后的结果也不一样,效率也不一样. Linq的执行效率对比 List<int> source = new List<int>(); ...
- DIV内容超出长度显示省略号,鼠标移上自动显示全部内容(EasyUI DataGrid)
如果想把DIV中超出的文本显示成省略号,而不是换行全部显示,有2个办法. 注:本文主要是以EasyUI的DataGrid为案例的,如果是其他场景只要底层是用DIV显示文本的应该都能使用. 首先可以给此 ...
- golang环境 centos 7
https://blog.csdn.net/ggq89/article/details/82682171 Linux下Go的安装.配置 .升级和卸载 https://blog.csdn.net/we ...
- BZOJ1880或洛谷2149 [SDOI2009]Elaxia的路线
BZOJ原题链接 洛谷原题链接 显然最长公共路径是最短路上的一条链. 我们可以把最短路经过的边看成有向边,那么组成的图就是一张\(DAG\),这样题目要求的即是两张\(DAG\)重合部分中的最长链. ...
- UI与开发的必备神器!— iDoc一键适配不同平台尺寸(iDoc201902-2新功能)
一.自动换算不同平台尺寸在一个项目从设计到开发的过程中,为了适配不同设备,一份设计稿,UI需要花大量的时间去制作各种尺寸的切图,耗时耗力. 那有没有一种高效的办法,让UI只需要设计一份设计稿就可以了呢 ...
- 游戏脚本编程 文本token解析
一个数字的组成由以下几个字符 正负号 + - 小数点 . 数字 0-9 比如 3 -3 3.13 -34.2234 但是符号和小数点不会出现多次 那么识别流程用图来表示 则是 整数 浮点数 一 ...
- selenium实现淘宝的商品爬取
一.问题 本次利用selenium自动化测试,完成对淘宝的爬取,这样可以避免一些反爬的措施,也是一种爬虫常用的手段.本次实战的难点: 1.如何利用selenium绕过淘宝的登录界面 2.获取淘宝的页面 ...
- 前端之html概述及基本结构
html概述: HTML是 HyperText Mark-up Language 的首字母简写,意思是超文本标记语言,超文本指的是超链接,标记指的是标签,是一种用来制作网页的语言,这种语言由一个个的标 ...