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. python重试(指数退避算法)

    本文实现了一个重试的装饰器,并且使用了指数退避算法.指数退避算法实现还是很简单的.先上代码再详细解释. 1.指数退避算法 欠奉.http://hugnew.com/?p=814 2.重试装饰器retr ...

  2. Win10下python3和python2同时安装并解决pip共存问题

    特别说明,本文是在Windows64位系统下进行的,32位系统请下载相应版本的安装包,安装方法类似. 使用python开发,环境有Python2和 python3 两种,有时候需要两种环境切换使用,下 ...

  3. Laplace(拉普拉斯)先验与L1正则化

    Laplace(拉普拉斯)先验与L1正则化 在之前的一篇博客中L1正则化及其推导推导证明了L1正则化是如何使参数稀疏化人,并且提到过L1正则化如果从贝叶斯的观点看来是Laplace先验,事实上如果从贝 ...

  4. 移动端效果之IndexList

    写在前面 接着前面的移动端效果讲,这次讲解的的是IndexList的实现原理.效果如下: 代码请看这里:github 移动端效果之swiper 移动端效果之picker 移动端效果之cellSwipe ...

  5. 表单处理的方案与注意事项(servlet)

    摘要 表单是后端程序员用的与接触最多的,我这里例举了常用处理办法,与注意事项 sevlet处理代码 package myform; import java.io.IOException; import ...

  6. MYSQL 总结

    1.数据库实质中访问的是 DBMC,数据库是一种存储介质 2.groub by 与 having 理解 group by 有一个原则,select后面的所有列中,没有使用聚合函数的列必须出现在 gro ...

  7. C++内联函数(03)

    在C++中我们通常定义以下函数来求两个整数的最大值: 代码如下: int max(int a, int b){ return a > b ? a : b;} 为这么一个小的操作定义一个函数的好处 ...

  8. tamcat的使用

    tomcat的基础知识 一.tomcat的定义 apache的官网是这么说的:使用Apache Tomcat ®软件了Java Servlet,JavaServer页,Java表达式语言和Java的W ...

  9. sql的基本知识

    一.什么是sql? 全称:"结构化查询语言(Structured  Query Language)",是1974年由Boyce和Chamberlin提出来的,现已经成为关系数据库的 ...

  10. Java基础笔记6

    OOP(Object Oriented Programmer) 面向对象编程     面向对象编程的语言:JAVA,C#,PHP,ASP 用途:把现实中的任何对象描述成java语言. java面向对象 ...