python subprocess模块

subprocess.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)python

 

 

这个模块主要包含一个Popen类shell

 

args能够是字符串或者序列类型(如:list,元组),用于指定进程的可执行文件及其参数。若是是序列类型,第一个元素一般是可执行文件的路径。咱们也能够显式的使用executeable参数来指定可执行文件的路径。在windows操做系统上,Popen经过调用CreateProcess()来建立子进程,CreateProcess接收一个字符串参数,若是args是序列类型,系统将会经过list2cmdline()函数将序列类型转换为字符串。windows


executable用于指定可执行程序。通常状况下咱们经过args参数来设置所要运行的程序。若是将参数shell设为True,executable将指定程序使用的shell。在windows平台下,默认的shell由COMSPEC环境变量来指定。函数


stdin, stdout, stderr分别表示程序的标准输入、输出、错误句柄。他们能够是PIPE,文件描述符或文件对象,也能够设置为None,表示从父进程继承。操作系统


preexec_fn只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行以前被调用。code


Close_sfs:在windows平台下,若是close_fds被设置为True,则新建立的子进程将不会继承父进程的输入、输出、错误管道。咱们不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。对象


shell=true,程序将经过shell来执行。
cwd用于设置子进程的当前目录。继承


env是字典类型,用于指定子进程的环境变量。若是env = None,子进程的环境变量将从父进程中继承。进程


Universal_newlines:不一样操做系统下,文本的换行符是不同的。如:windows下用'\r\n'表示换,而Linux下用'\n'。若是将此参数设置为True,Python统一把这些换行符看成'\n'来处理。ip


startupinfo与createionflags只在windows下用效,它们将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等。

 

subprocess.PIPE

  在建立Popen对象时,subprocess.PIPE能够初始化stdin, stdout或stderr参数。表示与子进程通讯的标准流。

 

subprocess.STDOUT

  建立Popen对象时,用于初始化stderr参数,表示将错误经过标准输出流输出。

 

Popen的方法:

Popen.poll()

  用于检查子进程是否已经结束。设置并返回returncode属性。

 

Popen.wait()

  等待子进程结束。设置并返回returncode属性。

 

Popen.communicate(input=None)

  与子进程进行交互。向stdin发送数据,或从stdout和stderr中读取数据。可选参数input指定发送到子进程的参数。Communicate()返回一个元组:(stdoutdata, stderrdata)。注意:若是但愿经过进程的stdin向其发送数据,在建立Popen对象的时候,参数stdin必须被设置为PIPE。一样,若是但愿从stdout和stderr获取数据,必须将stdout和stderr设置为PIPE。

 

Popen.send_signal(signal)

  向子进程发送信号。

 

Popen.terminate()

  中止(stop)子进程。在windows平台下,该方法将调用Windows API TerminateProcess()来结束子进程。

 

Popen.kill()

  杀死子进程。

 

Popen.stdin

  若是在建立Popen对象是,参数stdin被设置为PIPE,Popen.stdin将返回一个文件对象用于策子进程发送指令。不然返回None。

 

Popen.stdout

  若是在建立Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。不然返回None。

 

Popen.stderr

  若是在建立Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。不然返回None。

 

Popen.pid

  获取子进程的进程ID。

 

Popen.returncode

  获取进程的返回值。若是进程尚未结束,返回None。

下面是一个很是简单的例子,来演示supprocess模块如何与一个控件台应用程序进行交互。

 

You can kill the pragram,When the pragram is timeout...

for example:

#!/usr/bin/env python
#coding:utf-8
#author:Bing
import subprocess
import select,time,datetime
from config import cur_file_dir    

    run_script_path = cur_file_dir()+"/poc/"
    
    def poc_verify(self,target, poc_file,taskid = None):
        #run_env = '{"LD_LIBRARY_PATH": "/home/thorns/libs/"}'    
        if taskid == None:
            cmdline = 'python %s %s' % (poc_file,target)
        else:
            cmdline = 'python %s %s %s' % (poc_file,target, taskid)
        start = datetime.datetime.now()
        proc = subprocess.Popen(cmdline,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,cwd=self.run_script_path)
        #,env=run_env
        while proc.poll() is None:
            time.sleep(0.1)
            now = datetime.datetime.now()
            if (now - start).seconds > 10:
                try:
                    proc.kill()
                    print "Time is out! Process:%s;Target:%s"% (proc.pid,target)
                    return
                except Exception,e:
                    return None
                return None
        result = proc.communicate()[0]#proc.stdout.readlines()
        if proc.stdin:
            proc.stdin.close()
        if proc.stdout:
            proc.stdout.close()
        if proc.stderr:
            proc.stderr.close()
        if result:
            proc.kill()
            print result
        else:
            proc.kill()
相关文章
相关标签/搜索