python的subprocess模块(写的不错留作查询)
python的subprocess模块
subprocess模块是python从2.4版本开始引入的模块。主要用来取代 一些旧的模块方法,如os.system、os.spawn*、os.popen*、commands.*等。subprocess通过子进程来执行外部指令,并通过input/output/error管道,获取子进程的执行的返回信息。 常用方法: subprocess.call():执行命令,并返回执行状态,其中shell参数为False时,命令需要通过列表的方式传入,当shell为True时,可直接传入命令 示例如下: 复制代码
>>> a = subprocess.call(['df','-hT'],shell=False)
Filesystem Type Size Used Avail Use% Mounted on
/dev/sda2 ext4 94G 64G 26G 72% /
tmpfs tmpfs 2.8G 0 2.8G 0% /dev/shm
/dev/sda1 ext4 976M 56M 853M 7% /boot >>> a = subprocess.call('df -hT',shell=True)
Filesystem Type Size Used Avail Use% Mounted on
/dev/sda2 ext4 94G 64G 26G 72% /
tmpfs tmpfs 2.8G 0 2.8G 0% /dev/shm
/dev/sda1 ext4 976M 56M 853M 7% /boot >>> print a
0 复制代码 subprocess.check_call():用法与subprocess.call()类似,区别是,当返回值不为0时,直接抛出异常 示例: 复制代码
>>> a = subprocess.check_call('df -hT',shell=True)
Filesystem Type Size Used Avail Use% Mounted on
/dev/sda2 ext4 94G 64G 26G 72% /
tmpfs tmpfs 2.8G 0 2.8G 0% /dev/shm
/dev/sda1 ext4 976M 56M 853M 7% /boot
>>> print a
0
>>> a = subprocess.check_call('dfdsf',shell=True)
/bin/sh: dfdsf: command not found
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/subprocess.py", line 502, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'dfdsf' returned non-zero exit status 127
复制代码 subprocess.check_output():用法与上面两个方法类似,区别是,如果当返回值为0时,直接返回输出结果,如果返回值不为0,直接抛出异常。需要说明的是,该方法在python3.x中才有。 subprocess.Popen(): 在一些复杂场景中,我们需要将一个进程的执行输出作为另一个进程的输入。在另一些场景中,我们需要先进入到某个输入环境,然后再执行一系列的指令等。这个时候我们就需要使用到suprocess的Popen()方法。该方法有以下参数: args:shell命令,可以是字符串,或者序列类型,如list,tuple。 bufsize:缓冲区大小,可不用关心 stdin,stdout,stderr:分别表示程序的标准输入,标准输出及标准错误 shell:与上面方法中用法相同 cwd:用于设置子进程的当前目录 env:用于指定子进程的环境变量。如果env=None,则默认从父进程继承环境变量 universal_newlines:不同系统的的换行符不同,当该参数设定为true时,则表示使用\n作为换行符 示例1,在/root下创建一个suprocesstest的目录: >>> a = subprocess.Popen('mkdir subprocesstest',shell=True,cwd='/root') 示例2,使用python执行几个命令: 复制代码
import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n')
obj.stdin.write('print 2 \n')
obj.stdin.write('print 3 \n')
obj.stdin.write('print 4 \n')
obj.stdin.close() cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error = obj.stderr.read()
obj.stderr.close() print cmd_out
print cmd_error
复制代码 也可以使用如下方法: 复制代码
import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 \n')
obj.stdin.write('print 2 \n')
obj.stdin.write('print 3 \n')
obj.stdin.write('print 4 \n') out_error_list = obj.communicate()
print out_error_list
复制代码 示例3,将一个子进程的输出,作为另一个子进程的输入: import subprocess
child1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE)
child2 = subprocess.Popen(["grep","0:0"],stdin=child1.stdout, stdout=subprocess.PIPE)
out = child2.communicate() 其他方法: 复制代码
import subprocess
child = subprocess.Popen('sleep 60',shell=True,stdout=subprocess.PIPE)
child.poll() #检查子进程状态
child.kill() #终止子进程
child.send_signal() #向子进程发送信号
child.terminate() #终止子进程
原文作者:https://www.cnblogs.com/breezey/p/6673901.html
python的subprocess模块(写的不错留作查询)的更多相关文章
- Python中subprocess 模块 创建并运行一个进程
python的subprocess模块,看到官方声明里说要尽力避免使用shell=True这个参数,于是测试了一下: from subprocess import call import shlex ...
- python 利用python的subprocess模块执行外部命令,获取返回值
有时执行dos命令需要保存返回值 需要导入库subprocess import subprocess p = subprocess.Popen('ping www.baidu.com', shell= ...
- Python之subprocess模块、sys模块
一.subprocess模块 # import os # os.system('tasklist') #类似cmd输入系统命令 ''' subprocess的目的就是启动一个新的进程并且与之通信. s ...
- python的subprocess模块介绍
一.subprocess以及常用的封装函数运行python的时候,我们都是在创建并运行一个进程.像Linux进程那样,一个进程可以fork一个子进程,并让这个子进程exec另外一个程序.在Python ...
- python之subprocess模块详解--小白博客
subprocess模块 subprocess是Python 2.4中新增的一个模块,它允许你生成新的进程,连接到它们的 input/output/error 管道,并获取它们的返回(状态)码.这个模 ...
- python中subprocess模块
subprocess 模块 subprocess称之为子进程,进程是一个正在进行的程序 子进程是由另一个正在运行的程序启动的程序,例如QQ聊天点击一个链接,打开了浏览器,那么浏览器称之为QQ的子进程 ...
- python的subprocess模块执行shell命令
subprocess模块可以允许我们执行shell命令 一般来说,使用run()方法就可以满足大部分情况 使用run执行shell命令 In [5]: subprocess.run('echo &qu ...
- Python之Subprocess模块
PS:打开文件时候加b参数是代表以二进制方式打开,在Linux加不加都可以,在windows上面最好加b参数否则可能会出现问题 使用system返回执行结果不赋值,使用popen返回了结果赋值给cmd ...
- python基础--subprocess模块
可以执行shell命令的相关模块和函数有: os.system os.spawn* os.popen* --废弃 popen2.* --废弃 commands.* ...
随机推荐
- spring-data-cassanra的简单使用
之前写了JAVA操作cassandra驱动包,现在来看看spring-data对cassandra的支持.这里是spring-data-cassandra的官方文档:http://docs.sprin ...
- 开发商应用被App Store拒绝的79个原因
转自:http://www.gamelook.com.cn/2014/10/186017 作为iOS开发者,估计有很多都遇到过APP提交到App Store被拒,然后这些被拒的原因多种多样,今天小编收 ...
- 【转】python的复制,深拷贝和浅拷贝的区别
在python中,对象赋值实际上是对象的引用.当创建一个对象,然后把它赋给另一个变量的时候,python并没有拷贝这个对象,而只是拷贝了这个对象的引用 一般有三种方法, alist=[1,2,3,[& ...
- 原生及jq方式使用ajax
1.原生js实现Ajax方法: // 封装ajax()方法 function ajax(url,fnSucc,fnFaild){ //1.创建Ajax 对象 if(window.XMLHttpRequ ...
- openstack官方指导书
openstack官方网站:https://docs.openstack.org/ 由于openstack的官方文档有点多,所以这里对其进行梳理一下 Release Notes 发布版本 新功能,升级 ...
- Key and Certificate Conversion
Key and Certificate Conversion Private keys and certificates can be stored in a variety of formats, ...
- gin-swagger包Api文档生成, Post请求参数无法接收, 问题修复。
Bug描述 FormData方式下,任意参数类型都只生成file参数类型. 问题重现 问题代码在这一行 github.com\swaggo\swag\operation.go : 131 line c ...
- CF 148D D Bag of mice (概率dp)
题目链接 D. Bag of mice time limit per test 2 seconds memory limit per test 256 megabytes input standard ...
- Keras实现CIFAR-10分类
仅仅为了学习Keras的使用,使用一个四层的全连接网络对MNIST数据集进行分类,网络模型各层结点数为:3072: : 1024 : 512:10: 使用50000张图片进行训练,10000张 ...
- 检查浏览器是否有此插件如flash
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...