1 os.systemhtml
能夠返回運行shell命令狀態,同時會在終端輸出運行結果python
例如 ipython中運行以下命令,返回運行狀態statusshell
os.system('cat /etc/passwdqc.conf') min=disabled,24,11,8,7 max=40 passphrase=3 match=4 similar=deny random=47 enforce=everyone retry=3 Out[6]: 0
2 os.popen()app
能夠返回運行結果dom
popen(command [, mode='r' [, bufsize]]) -> pipe Open a pipe to/from a command returning a file object.
運行返回結果python2.7
In [20]: output = os.popen('cat /proc/cpuinfo') In [21]: lineLen = [] In [22]: for line in output.readlines(): lineLen.append(len(line)) ....: In [23]: line line lineLen In [23]: lineLen Out[23]: [14, 25, ...
3 如何同時返回結果和運行狀態,commands模塊:函數
#String form: <module 'commands' from '/usr/lib64/python2.7/commands.pyc'> File: /usr/lib64/python2.7/commands.py Docstring: Execute shell commands via os.popen() and return status, output. Interface summary: import commands outtext = commands.getoutput(cmd) (exitstatus, outtext) = commands.getstatusoutput(cmd) outtext = commands.getstatus(file) # returns output of "ls -ld file" A trailing newline is removed from the output string. Encapsulates the basic operation: pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r') text = pipe.read() sts = pipe.close()
commands示例以下:ui
In [24]: (status, output) = commands.getstatusoutput('cat /proc/cpuinfo') In [25]: status Out[25]: 0 In [26]: len(output) Out[26]: 3859
4 使用模塊subprocessthis
一般項目中常用方法爲subporcess.Popen, 咱們能夠在Popen()創建子進程的時候改變標準輸入、標準輸出和標準錯誤,並能夠利用subprocess.PIPE將多個子進程的輸入和輸出鏈接在一塊兒,構成管道(pipe):google
import subprocess child1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE) child2 = subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE) out = child2.communicate() print(out)
在例如使用lsblk查看swap分區的uuid:
import subprocess child = subprocess.Popen(["lsblk", "-f"], stdout=subprocess.PIPE) out = child.stdout.readlines() swap_uuid = None for item in out: line = item.strip().split() if len(line) == 4: if(line[1] == 'swap'): swap_uuid = line[2] print(swap_uuid)
ipython 中運行"?subprocess"能夠發現subprocess是python用來替換os.popen()等管道操做命令的新模塊
A more real-world example would look like this: try: retcode = call("mycmd" + " myarg", shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e
相對於上面幾種方式,subprocess便於控制和監控進程運行結果,subprocess提供多種函數便於應對父進程對子進程不一樣要求:
4.1.1 subprocess.call()
父進程父進程等待子進程完成,返回exit code
4.1.2 subprocess.check_call()
父進程等待子進程完成,返回0,若是returncode不爲0,則舉出錯誤subprocess.CalledProcessError,該對象包含有returncode屬性,可用try...except...來檢查
4.1.3 subprocess.check_output()
父進程等待子進程完成
返回子進程向標準輸出的輸出結果
檢查退出信息,若是returncode不爲0,則舉出錯誤subprocess.CalledProcessError,該對象包含有returncode屬性和output屬性,output屬性爲標準輸出的輸出結果,可用try...except...來檢查
例如:
In [32]: out = subprocess.call("ls -l", shell=True) total 42244 -rw-rw-r--. 1 *** *** 366 May 26 09:10 ChangeLog
4.2.1
上面三個函數都是源於Popen()函數的wapper(封裝),若是須要更加個性化應用,那麼就須要使用popen()函數
Popen對象建立後,主程序不會自動等待子進程完成。咱們必須調用對象的wait()方法,父進程纔會等待 (也就是阻塞block)
[wenwt@localhost syntax]$ rm subprocess.pyc [wenwt@localhost syntax]$ python process.py parent process [wenwt@localhost syntax]$ PING www.google.com (173.194.219.99) 56(84) bytes of data. ^C [wenwt@localhost syntax]$ --- www.google.com ping statistics --- 5 packets transmitted, 0 received, 100% packet loss, time 3999ms
加上wait方法:
[wenwt@localhost syntax]$ python process.py PING www.google.com (173.194.219.103) 56(84) bytes of data. --- www.google.com ping statistics --- 5 packets transmitted, 0 received, 100% packet loss, time 3999ms parent process