原始地址
subprocess是Python 2.4中新增的一個模塊,它容許你生成新的進程,鏈接到它們的 input/output/error 管道,並獲取它們的返回(狀態)碼。這個模塊的目的在於替換幾個舊的模塊和方法,如:html
os.system
os.spawn*python
在Python 3.5以後的版本中,官方文檔中提倡經過subprocess.run()函數替代其餘函數來使用subproccess模塊的功能;
在Python 3.5以前的版本中,咱們能夠經過subprocess.call(),subprocess.getoutput()等上面列出的其餘函數來使用subprocess模塊的功能;
subprocess.run()、subprocess.call()、subprocess.check_call()和subprocess.check_output()都是經過對subprocess.Popen的封裝來實現的高級函數,所以若是咱們須要更復雜功能時,能夠經過subprocess.Popen來完成。
subprocess.getoutput()和subprocess.getstatusoutput()函數是來自Python 2.x的commands模塊的兩個遺留函數。它們隱式的調用系統shell,而且不保證其餘函數所具備的安全性和異常處理的一致性。另外,它們從Python 3.3.4開始才支持Windows平臺。shell
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)api
subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)數組
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False, timeout=None)緩存
subprocess.getstatusoutput(cmd)安全
subprocess.getoutput(cmd)
複製代碼session
參數說明:
args: 要執行的shell命令,默認應該是一個字符串序列,如['df', '-Th']或('df', '-Th'),也能夠是一個字符串,如'df -Th',可是此時須要把shell參數的值置爲True。
shell: 若是shell爲True,那麼指定的命令將經過shell執行。若是咱們須要訪問某些shell的特性,如管道、文件名通配符、環境變量擴展功能,這將是很是有用的。固然,python自己也提供了許多相似shell的特性的實現,如glob、fnmatch、os.walk()、os.path.expandvars()、os.expanduser()和shutil等。
check: 若是check參數的值是True,且執行命令的進程以非0狀態碼退出,則會拋出一個CalledProcessError的異常,且該異常對象會包含 參數、退出狀態碼、以及stdout和stderr(若是它們有被捕獲的話)。
stdout, stderr:input: 該參數是傳遞給Popen.communicate(),一般該參數的值必須是一個字節序列,若是universal_newlines=True,則其值應該是一個字符串。
run()函數默認不會捕獲命令執行結果的正常輸出和錯誤輸出,若是咱們向獲取這些內容須要傳遞subprocess.PIPE,而後能夠經過返回的CompletedProcess類實例的stdout和stderr屬性或捕獲相應的內容;
call()和check_call()函數返回的是命令執行的狀態碼,而不是CompletedProcess類實例,因此對於它們而言,stdout和stderr不適合賦值爲subprocess.PIPE;
check_output()函數默認就會返回命令執行結果,因此不用設置stdout的值,若是咱們但願在結果中捕獲錯誤信息,能夠執行stderr=subprocess.STDOUT。
universal_newlines: 該參數影響的是輸入與輸出的數據格式,好比它的值默認爲False,此時stdout和stderr的輸出是字節序列;當該參數的值設置爲True時,stdout和stderr的輸出是字符串。ide
args: 用於加載該進程的參數,這多是一個列表或一個字符串
returncode: 子進程的退出狀態碼。一般狀況下,退出狀態碼爲0則表示進程成功運行了;一個負值-N表示這個子進程被信號N終止了
stdout: 從子進程捕獲的stdout。這一般是一個字節序列,若是run()函數被調用時指定universal_newlines=True,則該屬性值是一個字符串。若是run()函數被調用時指定stderr=subprocess.STDOUT,那麼stdout和stderr將會被整合到這一個屬性中,且stderr將會爲None
stderr: 從子進程捕獲的stderr。它的值與stdout同樣,是一個字節序列或一個字符串。若是stderr滅有被捕獲的話,它的值就爲None
check_returncode(): 若是returncode是一個非0值,則該方法會拋出一個CalledProcessError異常。函數
subprocess.run(["ls", "-l"]) # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)
subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')
複製代碼
subprocess.call()
複製代碼
subprocess.call(['ls', '-l'])
總用量 160
drwxr-xr-x 2 wader wader 4096 12月 7 2015 公共的
drwxr-xr-x 2 wader wader 4096 12月 7 2015 模板
drwxr-xr-x 2 wader wader 4096 12月 7 2015 視頻
drwxr-xr-x 2 wader wader 4096 12月 7 2015 圖片
drwxr-xr-x 2 wader wader 4096 12月 7 2015 文檔
drwxr-xr-x 2 wader wader 4096 4月 13 2016 下載
drwxr-xr-x 2 wader wader 4096 12月 7 2015 音樂
drwxr-xr-x 7 wader wader 4096 5月 26 2016 桌面
0
subprocess.call('ls -l', shell=True)
總用量 160
drwxr-xr-x 2 wader wader 4096 12月 7 2015 公共的
drwxr-xr-x 2 wader wader 4096 12月 7 2015 模板
drwxr-xr-x 2 wader wader 4096 12月 7 2015 視頻
drwxr-xr-x 2 wader wader 4096 12月 7 2015 圖片
drwxr-xr-x 2 wader wader 4096 12月 7 2015 文檔
drwxr-xr-x 2 wader wader 4096 4月 13 2016 下載
drwxr-xr-x 2 wader wader 4096 12月 7 2015 音樂
drwxr-xr-x 7 wader wader 4096 5月 26 2016 桌面
0
subprocess.call(['ls', '-l'], stdout=subprocess.DEVNULL)
0
subprocess.call(['ls', '-l', '/test'])
ls: 沒法訪問/test: 沒有那個文件或目錄
2
複製代碼
suprocess.check_call()
複製代碼
subprocess.check_call(['ls', '-l'])
總用量 160
drwxr-xr-x 2 wader wader 4096 12月 7 2015 公共的
drwxr-xr-x 2 wader wader 4096 12月 7 2015 模板
drwxr-xr-x 2 wader wader 4096 12月 7 2015 視頻
drwxr-xr-x 2 wader wader 4096 12月 7 2015 圖片
drwxr-xr-x 2 wader wader 4096 12月 7 2015 文檔
drwxr-xr-x 2 wader wader 4096 4月 13 2016 下載
drwxr-xr-x 2 wader wader 4096 12月 7 2015 音樂
drwxr-xr-x 7 wader wader 4096 5月 26 2016 桌面
0
subprocess.check_call('ls -l', shell=True)
總用量 160
drwxr-xr-x 2 wader wader 4096 12月 7 2015 公共的
drwxr-xr-x 2 wader wader 4096 12月 7 2015 模板
drwxr-xr-x 2 wader wader 4096 12月 7 2015 視頻
drwxr-xr-x 2 wader wader 4096 12月 7 2015 圖片
drwxr-xr-x 2 wader wader 4096 12月 7 2015 文檔
drwxr-xr-x 2 wader wader 4096 4月 13 2016 下載
drwxr-xr-x 2 wader wader 4096 12月 7 2015 音樂
drwxr-xr-x 7 wader wader 4096 5月 26 2016 桌面
0
subprocess.check_call('ls -l /test', shell=True)
ls: 沒法訪問/test: 沒有那個文件或目錄
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/subprocess.py", line 557, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'ls -l /test' returned non-zero exit status 2
複製代碼
sbuprocess.check_output()
複製代碼
ret = subprocess.check_output(['ls', '-l'])
print(ret)
b' \xe5\x85\xac\xe5\x85\xb1\xe7\x9a\x84\ndrwxr-xr-x 2 wader wader 4096 12\xe6\x9c\x88 7 2015 \xe6\xa8\xa1\xe6\x9d\xbf\ndrwxr-xr-x 2 wader wader 4096 12\xe6\x9c\x88 7 2015 \xe8\xa7\x86\xe9\xa2\x91\ndrwxr-xr-x 2 wader wader 4096 12\xe6\x9c\x88 7 2015 \xe5\x9b\xbe\xe7\x89\x87\ndrwxr-xr-x 2 wader wader 4096 12\xe6\x9c\x88 7 2015 \xe6\x96\x87\xe6\xa1\xa3\ndrwxr-xr-x 2 wader wader 4096 4\xe6\x9c\x88 13 2016 \xe4\xb8\x8b\xe8\xbd\xbd\ndrwxr-xr-x 2 wader wader 4096 12\xe6\x9c\x88 7 2015 \xe9\x9f\xb3\xe4\xb9\x90\ndrwxr-xr-x 7 wader wader 4096 5\xe6\x9c\x88 26 2016 \xe6\xa1\x8c\xe9\x9d\xa2\n'
ret = subprocess.check_output(['ls', '-l'], universal_newlines=True)
print(ret)
總用量 160
drwxr-xr-x 2 wader wader 4096 12月 7 2015 公共的
drwxr-xr-x 2 wader wader 4096 12月 7 2015 模板
drwxr-xr-x 2 wader wader 4096 12月 7 2015 視頻
drwxr-xr-x 2 wader wader 4096 12月 7 2015 圖片
drwxr-xr-x 2 wader wader 4096 12月 7 2015 文檔
drwxr-xr-x 2 wader wader 4096 4月 13 2016 下載
drwxr-xr-x 2 wader wader 4096 12月 7 2015 音樂
drwxr-xr-x 7 wader wader 4096 5月 26 2016 桌面
複製代碼
subprocess.getoutput()與subprocess.getstatusoutput()
複製代碼
ret = subprocess.getoutput('ls -l')
print(ret)
總用量 160
drwxr-xr-x 2 wader wader 4096 12月 7 2015 公共的
drwxr-xr-x 2 wader wader 4096 12月 7 2015 模板
drwxr-xr-x 2 wader wader 4096 12月 7 2015 視頻
drwxr-xr-x 2 wader wader 4096 12月 7 2015 圖片
drwxr-xr-x 2 wader wader 4096 12月 7 2015 文檔
drwxr-xr-x 2 wader wader 4096 4月 13 2016 下載
drwxr-xr-x 2 wader wader 4096 12月 7 2015 音樂
drwxr-xr-x 7 wader wader 4096 5月 26 2016 桌面
retcode, output = subprocess.getstatusoutput('ls -l')
print(retcode)
0
print(output)
總用量 160
drwxr-xr-x 2 wader wader 4096 12月 7 2015 公共的
drwxr-xr-x 2 wader wader 4096 12月 7 2015 模板
drwxr-xr-x 2 wader wader 4096 12月 7 2015 視頻
drwxr-xr-x 2 wader wader 4096 12月 7 2015 圖片
drwxr-xr-x 2 wader wader 4096 12月 7 2015 文檔
drwxr-xr-x 2 wader wader 4096 4月 13 2016 下載
drwxr-xr-x 2 wader wader 4096 12月 7 2015 音樂
drwxr-xr-x 7 wader wader 4096 5月 26 2016 桌面
retcode, output = subprocess.getstatusoutput('ls -l /test')
print(retcode)
2
print(output)
ls: 沒法訪問/test: 沒有那個文件或目錄
複製代碼
subprocess.Popen介紹
該類用於在一個新的進程中執行一個子程序。前面咱們提到過,上面介紹的這些函數都是基於subprocess.Popen類實現的,經過使用這些被封裝後的高級函數能夠很方面的完成一些常見的需求。因爲subprocess模塊底層的進程建立和管理是由Popen類來處理的,所以,當咱們沒法經過上面哪些高級函數來實現一些不太常見的功能時就能夠經過subprocess.Popen類提供的靈活的api來完成。
1.subprocess.Popen的構造函數
複製代碼
class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False,
startup_info=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=())
複製代碼
參數說明:
args: 要執行的shell命令,能夠是字符串,也能夠是命令各個參數組成的序列。當該參數的值是一個字符串時,該命令的解釋過程是與平臺相關的,所以一般建議將args參數做爲一個序列傳遞。
bufsize: 指定緩存策略,0表示不緩衝,1表示行緩衝,其餘大於1的數字表示緩衝區大小,負數 表示使用系統默認緩衝策略。
stdin, stdout, stderr: 分別表示程序標準輸入、輸出、錯誤句柄。
preexec_fn: 用於指定一個將在子進程運行以前被調用的可執行對象,只在Unix平臺下有效。
close_fds: 若是該參數的值爲True,則除了0,1和2以外的全部文件描述符都將會在子進程執行以前被關閉。
shell: 該參數用於標識是否使用shell做爲要執行的程序,若是shell值爲True,則建議將args參數做爲一個字符串傳遞而不要做爲一個序列傳遞。
cwd: 若是該參數值不是None,則該函數將會在執行這個子進程以前改變當前工做目錄。
env: 用於指定子進程的環境變量,若是env=None,那麼子進程的環境變量將從父進程中繼承。若是env!=None,它的值必須是一個映射對象。
universal_newlines: 若是該參數值爲True,則該文件對象的stdin,stdout和stderr將會做爲文本流被打開,不然他們將會被做爲二進制流被打開。
startupinfo和creationflags: 這兩個參數只在Windows下有效,它們將被傳遞給底層的CreateProcess()函數,用於設置子進程的一些屬性,如主窗口的外觀,進程優先級等。
import subprocess
p = subprocess.Popen('df -Th', stdout=subprocess.PIPE, shell=True)
print(p.stdout.read())
Filesystem Type Size Used Avail Use% Mounted on
/dev/vda1 ext4 40G 12G 26G 31% /
devtmpfs devtmpfs 3.9G 0 3.9G 0% /dev
tmpfs tmpfs 3.9G 0 3.9G 0% /dev/shm
tmpfs tmpfs 3.9G 386M 3.5G 10% /run
tmpfs tmpfs 3.9G 0 3.9G 0% /sys/fs/cgroup
tmpfs tmpfs 783M 0 783M 0% /run/user/0
tmpfs tmpfs 783M 0 783M 0% /run/user/1000
複製代碼
實例2:
複製代碼
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print(1) \n')
obj.stdin.write('print(2) \n')
obj.stdin.write('print(3) \n')
out,err = obj.communicate()
print(out)
1
2
3
print(err)
複製代碼
實例3:
複製代碼
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err = obj.communicate(input='print(1) \n')
print(out)
1print(err)
複製代碼
實例4:
實現相似df -Th | grep data命令的功能,實際上就是實現shell中管道的共功能。
複製代碼
p1 = subprocess.Popen(['df', '-Th'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['grep', 'data'], stdin=p1.stdout, stdout=subprocess.PIPE)
out,err = p2.communicate()
print(out)
/dev/vdb1 ext4 493G 4.8G 463G 2% /data
/dev/vdd1 ext4 1008G 420G 537G 44% /data1
/dev/vde1 ext4 985G 503G 432G 54% /data2print(err)
None
複製代碼
4、總結
那麼咱們到底該用哪一個模塊、哪一個函數來執行命令與系統及系統進行交互呢?下面咱們來作個總結:
首先應該知道的是,Python2.4版本引入了subprocess模塊用來替換os.system()、os.popen()、os.spawn*()等函數以及commands模塊;也就是說若是你使用的是Python 2.4及以上的版本就應該使用subprocess模塊了。若是你的應用使用的Python 2.4以上,可是是Python 3.5如下的版本,Python官方給出的建議是使用subprocess.call()函數。Python 2.5中新增了一個subprocess.check_call()函數,Python 2.7中新增了一個subprocess.check_output()函數,這兩個函數也能夠按照需求進行使用。若是你的應用使用的是Python 3.5及以上的版本(目前應該還不多),Python官方給出的建議是儘可能使用subprocess.run()函數。當subprocess.call()、subprocess.check_call()、subprocess.check_output()和subprocess.run()這些高級函數沒法知足需求時,咱們可使用subprocess.Popen類來實現咱們須要的複雜功能。