http://www.cnblogs.com/vamei/archive/2012/09/23/2698014.html

http://blog.csdn.net/jgood/article/details/4498166

http://docs.python.org/library/subprocess

subprocess.call()

[root@typhoeus79 20130925]# more test.py
#!/usr/bin/env python2.7
#-*- coding:utf8 -*- import subprocess rc = subprocess.call(["ls","-l"]) print "rc = ",rc
[root@typhoeus79 20130925]# ./test.py
total 4
-rwxr-xr-x 1 root root 118 Sep 25 11:18 test.py
rc = 0

将程序名ls和其对应的参数放在一个list中传给subprocess.call()

通过一个shell来解释字符串

[root@typhoeus79 20130925]# ./sub_shell.py
total 4
-rwxr-xr-x 1 root root 125 Sep 25 11:22 sub_shell.py
rc = 0
[root@typhoeus79 20130925]# more sub_shell.py
#!/usr/bin/env python2.7
#-*- coding:utf8 -*- import subprocess rc = subprocess.call("ls -l",shell=True) print "rc = ",rc

使用shell=True这个参数,使用字符串而不是使用list来运行子进程。python先运行一个shell,然后这个shell来解释整个字符串

Popen

基于Popen()的封装(wrapper),这些封装的目的在于让我们容易使用子进程。当我们想要更个性化我们的需求的时候,就要转向Popen类,该类生成的对象用来代表子进程

    Using the subprocess module
===========================
This module defines one class called Popen: class Popen(args, bufsize=0, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0):
[root@typhoeus79 20130925]# ./sub_popen.py
parent process
<subprocess.Popen object at 0x7fed17542050>
[root@typhoeus79 20130925]# PING www.a.shifen.com (220.181.111.148) 56(84) bytes of data. --- www.a.shifen.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 4002ms [root@typhoeus79 20130925]# more sub_popen.py
#!/usr/bin/env python26
#-*- coding:utf8 -*- import subprocess child = subprocess.Popen(["ping","-c","","www.baidu.com"])
#child = subprocess.Popen("ping -c5 www.baidu.com",shell=True) print("parent process")
print child

父进程在开启子进程之后没有等到其完成,而是直接print

改成等待模式:

[root@typhoeus79 20130925]# ./sub_popen.py
PING www.a.shifen.com (220.181.112.143) 56(84) bytes of data. --- www.a.shifen.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 4001ms parent process
<subprocess.Popen object at 0x7fe424c34050>
[root@typhoeus79 20130925]# more sub_popen.py
#!/usr/bin/env python26
#-*- coding:utf8 -*- import subprocess child = subprocess.Popen(["ping","-c","","www.baidu.com"]) child.wait()
print("parent process")
print child

父进程中对子进程进行其他操作:

child.poll() #检查子进程状态

child.kill() #终止子进程

child.send_signal() #向子进程发送信号

child.terminate() #终止子进程

子进程的PID存储在child.pid中

子进程的文本流控制

子进程的标准输入、标准输出、标准错误通过如下属性:

{'_child_created': True, 'returncode': 1, 'stdout': None, 'stdin': None, 'pid': 7070, 'stderr': None, 'universal_newlines': False}

child.stdin

child.stdout

child.stderr

可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出在一起,构成管道pipe:

[root@typhoeus79 20130925]# more sub_pipe.py
#!/usr/bin/env python26
#-*- coding:utf8 -*- import subprocess child1 = subprocess.Popen(["ls","-l"],stdout=subprocess.PIPE) child2 = subprocess.Popen(["wc"],stdin=child1.stdout,stdout=sub
process.PIPE) out = child2.communicate() print out
[root@typhoeus79 20130925]# ./sub_pipe.py
(' 4 29 167\n', None)

1、child1的stdout将文本输出缓存到subprocess.PIPE中

2、child2的stdin从child1的stdout读取文本

3、child2的输出文本也被存储在subprocess.PIPE中

4、communicate()方法从PIPE中读取相应的文本

communicate是Popen对象的一个方法,该方法会阻塞父进程,直到子进程完成。

    communicate(input=None)
Interact with process: Send data to stdin. Read data from stdout
and stderr, until end-of-file is reached. Wait for process to
terminate. The optional input argument should be a string to be
sent to the child process, or None, if no data should be sent to
the child. communicate() returns a tuple (stdout, stderr). Note: The data read is buffered in memory, so do not use this
method if the data size is large or unlimited.

可以使用communicate()方法使用PIPE给子进程输入:

#!/usr/bin/env python26
#-*- coding:utf8 -*- import subprocess
import time child = subprocess.Popen(["cat"],stdin=subprocess.PIPE) time.sleep(5)
child.communicate("Hello\n")

通过time.sleep也可以看到communicate是阻塞父进程

对python执行系统命令的封装

def sys_command(system_cmd):
logger.debug("system_cmd = '%s'." %system_cmd)
pipe = subprocess.Popen(system_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,stdin=subprocess.PIPE) stdout, stderr = pipe.communicate()
returncode = pipe.returncode logger.debug("returncode = '%d'." %returncode)
logger.debug("stdout = '%s'." %stdout)
logger.debug("stderr = '%s'." %stderr) return returncode,stdout,stderr

Python之子进程subprocess模块的更多相关文章

  1. python笔记之subprocess模块

    python笔记之subprocess模块 [TOC] 从Python 2.4开始,Python引入subprocess模块来管理子进程,以取代一些旧模块的方法:如 os.system.os.spaw ...

  2. Python中的subprocess模块

    Subprocess干嘛用的? subprocess模块是python从2.4版本开始引入的模块.主要用来取代 一些旧的模块方法,如os.system.os.spawn*.os.popen*.comm ...

  3. python学习之-- subprocess模块

    subprocess 模块 功能:用来生成子进程,并可以通过管道连接它们的输入/输出/错误,以及获得它们的返回值.它用来代替多个旧模块和函数: os.system os.spawn* os.popen ...

  4. Python中使用subprocess模块远程执行命令

    使用subprocess模块执行远程命令 服务端代码 1 import socket 2 import subprocess 3 4 sh_server = socket.socket() 5 sh_ ...

  5. python学习之subprocess模块

    subprocess.Popen 这个模块主要就提供一个类Popen: class subprocess.Popen( args, bufsize=0, executable=None, stdin= ...

  6. random模块、os模块、序列化模块、sy模块s、subprocess模块

    random随机数模块 random.random( ) 随机产生一个0-1之间的小数 print(random.random()) # 0.31595547439342897 random.rand ...

  7. Python subprocess模块学习总结

    从Python 2.4开始,Python引入subprocess模块来管理子进程,以取代一些旧模块的方法:如 os.system.os.spawn*.os.popen*.popen2.*.comman ...

  8. 子进程管理模块subprocess

    subprocess模块允许你生成子进程,连接管道,并获取返回的代码. 一.使用subprocess模块 模块中定义了一个Popen类:       subprocess.Popen(args, bu ...

  9. Python学习笔记——基础篇【第六周】——Subprocess模块

    执行系统命令 可以执行shell命令的相关模块和函数有: os.system os.spawn* os.popen*          --废弃 popen2.*           --废弃 com ...

随机推荐

  1. javascript中call()、apply()、bind()的用法终于理解

    其实是一个很简单的东西,认真看十分钟就从一脸懵B 到完全 理解! 先看明白下面: 例1 obj.objAge;  //17 obj.myFun()  //小张年龄undefined 例2 shows( ...

  2. hadoop配置文件详解,安装及相关操作

    一.      Hadoop伪分布配置 1. 在conf/hadoop-env.sh文件中增加:export JAVA_HOME=/home/Java/jdk1.6  2.  在conf/core-s ...

  3. java web Servlet 学习笔记 -3 会话管理技术

     Cookie和HttpSession 什么是会话: 用户开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话. 每个用户在使用浏览器与服务器进行会话的过 ...

  4. html加载时事件触发顺序

    一般情况下页面的响应加载顺序时,域名解析-加载html-加载js和css-加载图片等其他信息. jq ready()的方法就是Dom Ready,他的作用或者意义就是:在DOM加载完成后就可以可以对D ...

  5. ABP增删改查代码片段

    @using System.Web.Optimization @using MultiPageSimpleTask.Entitys.Dtos; @model IList<ProductDto&g ...

  6. SqlServer和Oracle中一些常用的sql语句9 SQL优化

    --SQL查询优化 尽量避免使用or,not,distinct运算符,简化连接条件 /*Or运算符*/ use db_business go select * from 仓库 where 城市='北京 ...

  7. Arrays.asList () 不可添加或删除元素的原因

    Java中奖数组转换为List<T>容器有一个很方便的方法 Arrays.asList(T ... a),我通过此方法给容器进行了赋值操作,接着对其进行 添加元素,却发现会抛出一个(jav ...

  8. 使用binlog2sql做数据恢复的简单示例

    有时我们会遇到操作人员误删或者误更新数据的情况,这时我们迫切希望把原来的数据还原回来,今天我们介绍一个简单的工具来方便的实现此功能. 前提条件 在实现数据恢复之前,需要我们的MySQL满足以下配置条件 ...

  9. UWP取出图片主色调

    一切都要从风车动漫的新详情页说起... 当我最初拿到风车动漫新详情页的UI设计概念图时,新详情页中有两点: 1.图片的高斯模糊 2.取出图片的主色调(主要用于tag和相关动漫的标题背景) 大概就是要这 ...

  10. Spring读书笔记——bean创建(上)

    通过<Spring读书笔记--bean加载>和<Spring读书笔记--bean解析>,我们明白了两件事. Spring如何加载消化一个xml配置文件 Spring如何将xml ...