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()
複製代碼

 


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