Python_cmd的各种实现方法及优劣(subprocess.Popen, os.system和commands.getstatusoutput)

http://blog.csdn.net/menglei8625/article/details/7494094

http://www.cnblogs.com/ballwql/p/install_gcc_python.html

目前我使用到的python中执行cmd的方式有三种:


1. 使用os.system("cmd")

这是最简单的一种方法,特点是执行的时候程序会打出cmd在Linux上执行的信息。使用前需要import os。

  1. os.system("ls")  

2. 使用Popen模块产生新的process

现在大部分人都喜欢使用Popen。Popen方法不会打印出cmd在linux上执行的信息。的确,Popen非常强大,支持多种参数和模式。使用前需要from subprocess import Popen, PIPE。但是Popen函数有一个缺陷,就是它是一个阻塞的方法。如果运行cmd时产生的内容非常多,函数非常容易阻塞住。解决办法是不使用wait()方法,但是也不能获得执行的返回值了。

Popen原型是:

  1. 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)  

参数bufsize:指定缓冲。我到现在还不清楚这个参数的具体含义,望各个大牛指点。

参数executable用于指定可执行程序。一般情况下我们通过args参数来设置所要运行的程序。如果将参数shell设为 True,executable将指定程序使用的shell。在windows平台下,默认的shell由COMSPEC环境变量来指定。

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

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

参数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’来处理。

参数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。


例如:

  1. p = Popen("cp -rf a/* b/", shell=True, stdout=PIPE, stderr=PIPE)  
  2. p.wait()  
  3. if p.returncode != 0:  
  4.     print "Error."  
  5.     return -1  

3. 使用commands.getstatusoutput方法

这个方法也不会打印出cmd在linux上执行的信息。这个方法唯一的优点是,它不是一个阻塞的方法。即没有Popen函数阻塞的问题。使用前需要import commands。

例如:

  1. status, output = commands.getstatusoutput("ls")  

还有只获得output和status的方法:
  1. commands.getoutput("ls")  
  2. commands.getstatus("ls")  


GCC源码自动编译-python脚本


一、前言

    目前因机器OS GCC版本太老,导致无法编译一些新版本软件,所以写了一个自动编译GCC的python脚本,操作系统是比较老的suse 10, 很多系统自动软件版本都很低,所以此脚本一般可适用目前比较流行的OS,大家可多尝试一下

二、机器环境

OS: SUSE 10 

Bit: 64-bit

python: 2.6

 

三、依赖软件

复制代码
gmp: 4.3.2

mpc: 0.8.1

mpfr: 2.4.2

gcc: 4.4.0
复制代码

 

四、安装脚本

1 目录结构

复制代码
InstallGcc

---bin

-----install_gcc.py

---conf

---tmp

---src

-----gcc

-------gmp-4.3.2.tar.gz

-------mpc-0.8.1.tar.gz

-------mpfr-2.4.2.tar.gz

-------gcc-4.4.0.tar.gz
复制代码

 

 

2 脚本如下:

复制代码
#!/usr/bin/env python
import sys,os,time,commands
import logging,logging.handlers

class InstallGcc(object):
    def __init__(self):
        self.base_dir=os.path.abspath(os.path.join(os.path.dirname(__file__),os.pardir))
        self.logger = self.get_logger()
        self.install_pardir='/usr/local'
        self.tmp_dir = '%s/tmp' % self.base_dir
        self.install_srcdir='%s/src/gcc' % self.base_dir
        self.dependList={'gmp':{'version':'4.3.2','srcfile':'gmp-4.3.2.tar.bz2'},'mpc':{'version':'0.8.1','srcfile':'mpc-0.8.1.tar.gz'},'mpfr':{'version':'2.4.2','srcfile':'mpfr-2.4.2.tar.bz2'},'gcc':{'version':'4.4.0','srcfile':'gcc-4.4.0.tar.gz'}}
        self.process_num = self.get_process_num()
    
    def get_logger(self):
        logname = '%s/log/install_gcc.log' % self.base_dir
        logger=logging.getLogger('install_mysql')
        logger.setLevel(logging.DEBUG)
        handler=logging.handlers.RotatingFileHandler(logname,maxBytes=4194304,backupCount=100)
        formatter = logging.Formatter('%(asctime)s %(filename)s:%(lineno)d [%(levelname)s]  %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        return logger
    def get_process_num(self):
        cmd="cat /proc/cpuinfo |grep processor|wc -l"
        ret = self.get_exec_result(cmd)
        return ret[1] 
    def get_exec_result(self,cmd):
        ret = commands.getstatusoutput(cmd)
        if ret[0] != 0:
            self.logger.error("%s:%s",cmd,ret[1])
            sys.exit(1)
        return ret
    def decompress_soft(self,name):
        try:
            srcfile=self.dependList[name]['srcfile']
            if srcfile.endswith('bz2'):
                cmd = "tar -jxvf %s/%s -C %s" % (self.install_srcdir,srcfile,self.tmp_dir)
            elif srcfile.endswith('gz'):
                cmd = "tar -zxvf %s/%s -C %s" % (self.install_srcdir,srcfile,self.tmp_dir)
            ret = self.get_exec_result(cmd)
            untar_dir = "%s/%s-%s" % (self.tmp_dir,name,self.dependList[name]['version'])
            os.chdir(untar_dir)
        except Exception,e:
            self.logger.error("decompress error:%s",e)
            sys.exit(1)
    def install_gmp(self):
        try:
            install_dir='%s/gmp-%s' % (self.install_pardir,self.dependList['gmp']['version'])
            if os.path.isdir(install_dir):
                msg = "gmp has been existed,continuing next step"
                print msg
                self.logger.error(msg)
            else:
                self.decompress_soft('gmp')
                cmd = "./configure --prefix=%s" % install_dir
                ret = self.get_exec_result(cmd)
                cmd = "make -j %s && make install" % (self.process_num)
                ret = self.get_exec_result(cmd)
                msg = "gmp installed ok,continuing next step"
                print msg
                self.logger.debug(msg)    
        except Exception,e:
            self.logger.error("install gmp error:%s",e)
            sys.exit(1)
    def install_mpfr(self):
        try:
            install_dir = '%s/mpfr-%s' % (self.install_pardir,self.dependList['mpfr']['version'])
            if os.path.isdir(install_dir):
                msg = "mpfr has been existed,continuing next step"
                print msg
                self.logger.error(msg)
            else:
                self.decompress_soft('mpfr')
                cmd = "./configure --prefix=%s --with-gmp=%s/gmp-%s" % (install_dir,self.install_pardir,self.dependList['gmp']['version'])
                ret = self.get_exec_result(cmd)
                cmd = "make -j %s && make install" % self.process_num
                ret = self.get_exec_result(cmd)
                msg = "mpfr installed ok,continuing next step"
                print msg
                self.logger.debug(msg)
        except Exception,e:
            self.logger.error("install mpfr error:%s",e)
            sys.exit(1)
    def install_mpc(self):
        try:
            install_dir = '%s/mpc-%s' % (self.install_pardir,self.dependList['mpc']['version'])
            if os.path.isdir(install_dir):
                msg = "mpc has been existed,continuing next step"
                print msg
                self.logger.error(msg)
            else:
                self.decompress_soft('mpc')
                cmd = " ./configure --prefix=%s --with-gmp=%s/gmp-%s --with-mpfr=%s/mpfr-%s" % (install_dir,self.install_pardir,self.dependList['gmp']['version'],self.install_pardir,self.dependList['mpfr']['version'])
                ret = self.get_exec_result(cmd)
                cmd = "make -j %s && make install" % self.process_num
                ret = self.get_exec_result(cmd)
                msg = "mpc installed ok,continuing next step"
                print msg
                self.logger.debug(msg)
        except Exception,e:
            self.logger.error("install mpc error:%s",e)
            sys.exit(1)
    def install_gcc(self):
        try:
            install_dir = '%s/gcc-%s' % (self.install_pardir,self.dependList['gcc']['version'])    
            if os.path.isdir(install_dir):
                msg = "gcc has been existed,continuing next step"
                print msg
                self.logger.error(msg)
            else:
                self.decompress_soft('gcc')
                
                gmp_dir= "%s/gmp-%s" % (self.install_pardir,self.dependList['gmp']['version'])
                mpfr_dir = "%s/mpfr-%s" % (self.install_pardir,self.dependList['mpfr']['version'])
                mpc_dir = "%s/mpc-%s" % (self.install_pardir,self.dependList['mpc']['version'])
                enable_con = "--enable-shared --enable-threads=posix --enable-languages=c,c++,objc,obj-c++"
                cmd = "export LD_LIBRARY_PATH=%s/lib:%s/lib:%s/lib:$LD_LIBRARY_PATH" % (gmp_dir,mpfr_dir,mpc_dir)
                ret = self.get_exec_result(cmd)
                cmd = "./configure --prefix=%s --with-gmp=%s --with-mpfr=%s --with-mpc=%s %s" % (install_dir,gmp_dir,mpfr_dir,mpc_dir,enable_con)
                ret = self.get_exec_result(cmd)
                cmd = "make -j %s && make install" % self.process_num
                ret = self.get_exec_result(cmd)
                msg = "gcc installed ok,work done"
                print msg
                self.logger.debug(msg)
        except Exception,e:
            self.logger.error("install gcc error:%s",e)
            sys.exit(1)
    def print_start(self,obj):
        msg="%s install........[START]" % obj
        self.logger.debug(msg)
        print msg
    def print_end(self,obj):
        msg="%s install.......[DONE]" % obj
        self.logger.debug(msg)
        print msg
    def run_install(self):
        self.print_start('gmp')
        self.install_gmp()
        self.print_end('gmp')
        self.print_start('mpfr')
        self.install_mpfr()
        self.print_end('mpfr')
        self.print_start('mpc')
        self.install_mpc()
        self.print_end('mpc')
        self.print_start('gcc')
        self.install_gcc()
        self.print_end('gcc')
if __name__ == '__main__':
    obj = InstallGcc()
    obj.run_install()
复制代码

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章