【轉】Python之系統互動(subprocess)
本節內容
- os與commands模組
- subprocess模組
- subprocess.Popen類
- 總結
我們幾乎可以在任何作業系統上通過命令列指令與作業系統進行互動,比如Linux平臺下的shell。那麼我們如何通過Python來完成這些命令列指令的執行呢?另外,我們應該知道的是命令列指令的執行通常有兩個我們比較關注的結果:
- 命令執行的狀態碼--表示命令執行是否成功
- 命令執行的輸出結果--命令執行成功後的輸出
早期的Python版本中,我們主要是通過os.system()、os.popen().read()等函式來執行命令列指令的,另外還有一個很少使用的commands模組。但是從Python 2.4開始官方文件中建議使用的是subprocess模組,所以os模組和commands模組的相關函式在這裡只提供一個簡單的使用示例,我們重要要介紹的是subprocess模組。
一、os與commands模組
Python中提供了以下幾個函式來幫助我們完成命令列指令的執行:
函式名 | 描述 |
---|---|
os.system(command) | 返回命令執行狀態碼,而將命令執行結果輸出到螢幕 |
os.popen(command).read() | 可以獲取命令執行結果,但是無法獲取命令執行狀態碼 |
commands.getstatusoutput(command) | 返回一個元組(命令執行狀態碼, 命令執行結果) |
說明:
- os.popen(command)函式得到的是一個檔案物件,因此除了read()方法外還支援write()等方法,具體要根據command來定;
- commands模組只存在於Python 2.7中,且不支援windows平臺,因此commands模組很少被使用。另外,commands模組實際上也是通過對os.popen()的封裝來完成的。
1. os.system()函式例項
>>> import os >>> >>> retcode = os.system('dir') 驅動器 C 中的卷沒有標籤。 卷的序列號是 4C32-B292 C:\Users\wader\PycharmProjects\LearnPython 的目錄 2017/03/21 11:15 <DIR> . 2017/03/21 11:15 <DIR> .. 2017/07/29 18:04 <DIR> .idea 2016/12/06 11:19 <DIR> blog 2016/12/06 11:42 <DIR> day01 2016/12/09 22:07 <DIR> day02 2017/01/04 09:14 <DIR> day03 2017/07/19 16:11 <DIR> day04 2017/07/29 14:44 <DIR> day05 2017/07/06 14:45 <DIR> day06 2017/07/06 17:13 <DIR> exam01 0 個檔案 0 位元組 11 個目錄 6,659,977,216 可用位元組 >>> retcode 0 >>>
2. os.popen()函式例項
>>> import os
>>>
>>> ret = os.popen('dir').read()
>>> print(ret)
驅動器 C 中的卷沒有標籤。
卷的序列號是 4C32-B292
C:\Users\wader\PycharmProjects\LearnPython 的目錄
2017/03/21 11:15 <DIR> .
2017/03/21 11:15 <DIR> ..
2017/07/29 18:04 <DIR> .idea
2016/12/06 11:19 <DIR> blog
2016/12/06 11:42 <DIR> day01
2016/12/09 22:07 <DIR> day02
2017/01/04 09:14 <DIR> day03
2017/07/19 16:11 <DIR> day04
2017/07/29 14:44 <DIR> day05
2017/07/06 14:45 <DIR> day06
2017/07/06 17:13 <DIR> exam01
0 個檔案 0 位元組
11 個目錄 6,664,052,736 可用位元組
>>>
3. commands.getstatusoutput()函式例項
需要注意的是commands模組不支援windows平臺,因此該例項是在Linux平臺下執行的
>>> import os
>>> os.system('ls')
cmdline-jmxclient-0.10.3.jar dhparam.pem FtpMan.class gitlab.crt gitlab.csr gitlab.key resolv.txt test.json test.php test.sh test.text test.txt
0
>>> import commands
>>> retcode, ret = commands.getstatusoutput('ls -l')
>>> retcode
0
>>> print(ret)
total 68
-rw-r--r-- 1 root root 20124 Jul 11 2016 cmdline-jmxclient-0.10.3.jar
-rw-r--r-- 1 root root 424 Aug 22 2016 dhparam.pem
-rw-r--r-- 1 root root 2576 Jul 13 2016 FtpMan.class
-rw-r--r-- 1 root root 1302 Aug 22 2016 gitlab.crt
-rw-r--r-- 1 root root 1054 Aug 22 2016 gitlab.csr
-rw-r--r-- 1 root root 1675 Aug 22 2016 gitlab.key
-rw-r--r-- 1 root root 9329 Jun 24 2016 resolv.txt
-rw-r--r-- 1 root root 594 Mar 7 08:14 test.json
-rw-r--r-- 1 root root 162 Jun 28 10:39 test.php
-rw-r--r-- 1 root root 760 Jun 24 2016 test.sh
-r-x------ 1 root root 0 Feb 6 08:21 test.text
drwxr-xr-x 2 root root 4096 Feb 7 16:43 test.txt
>>>
通過檢視commands模組提供的屬性可知,它也提供了單獨獲取命令執行狀態碼和執行結果的函式,如下所示:
>>> dir(commands)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'getoutput', 'getstatus', 'getstatusoutput', 'mk2arg', 'mkarg']
二、subprocess模組
subprocess是Python 2.4中新增的一個模組,它允許你生成新的程序,連線到它們的 input/output/error 管道,並獲取它們的返回(狀態)碼。這個模組的目的在於替換幾個舊的模組和方法,如:
- os.system
- os.spawn*
1. subprocess模組中的常用函式
函式 | 描述 |
---|---|
subprocess.run() | Python 3.5中新增的函式。執行指定的命令,等待命令執行完成後返回一個包含執行結果的CompletedProcess類的例項。 |
subprocess.call() | 執行指定的命令,返回命令執行狀態,其功能類似於os.system(cmd)。 |
subprocess.check_call() | Python 2.5中新增的函式。 執行指定的命令,如果執行成功則返回狀態碼,否則丟擲異常。其功能等價於subprocess.run(..., check=True)。 |
subprocess.check_output() | Python 2.7中新增的的函式。執行指定的命令,如果執行狀態碼為0則返回命令執行結果,否則丟擲異常。 |
subprocess.getoutput(cmd) | 接收字串格式的命令,執行命令並返回執行結果,其功能類似於os.popen(cmd).read()和commands.getoutput(cmd)。 |
subprocess.getstatusoutput(cmd) | 執行cmd命令,返回一個元組(命令執行狀態, 命令執行結果輸出),其功能類似於commands.getstatusoutput()。 |
說明:
- 在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平臺。
2. 上面各函式的定義及引數說明
函式引數列表:
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, universal_newlines=False)
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)
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)
引數說明:
- 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:
- run()函式預設不會捕獲命令執行結果的正常輸出和錯誤輸出,如果我們向獲取這些內容需要傳遞subprocess.PIPE,然後可以通過返回的CompletedProcess類例項的stdout和stderr屬性或捕獲相應的內容;
- call()和check_call()函式返回的是命令執行的狀態碼,而不是CompletedProcess類例項,所以對於它們而言,stdout和stderr不適合賦值為subprocess.PIPE;
- check_output()函式預設就會返回命令執行結果,所以不用設定stdout的值,如果我們希望在結果中捕獲錯誤資訊,可以執行stderr=subprocess.STDOUT。
- input: 該引數是傳遞給Popen.communicate(),通常該引數的值必須是一個位元組序列,如果universal_newlines=True,則其值應該是一個字串。
- universal_newlines: 該引數影響的是輸入與輸出的資料格式,比如它的值預設為False,此時stdout和stderr的輸出是位元組序列;當該引數的值設定為True時,stdout和stderr的輸出是字串。
3. subprocess.CompletedProcess類介紹
需要說明的是,subprocess.run()函式是Python3.5中新增的一個高階函式,其返回值是一個subprocess.CompletedPorcess類的例項,因此,subprocess.completedPorcess類也是Python 3.5中才存在的。它表示的是一個已結束程序的狀態資訊,它所包含的屬性如下:
- 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異常。
4. 例項
subprocess.run()
>>> 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 1
>>> subprocess.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()函式,用於設定子程序的一些屬性,如主視窗的外觀,程序優先順序等。
2. subprocess.Popen類的例項可呼叫的方法
方法 | 描述 |
---|---|
Popen.poll() | 用於檢查子程序(命令)是否已經執行結束,沒結束返回None,結束後返回狀態碼。 |
Popen.wait(timeout=None) | 等待子程序結束,並返回狀態碼;如果在timeout指定的秒數之後程序還沒有結束,將會丟擲一個TimeoutExpired異常。 |
Popen.communicate(input=None, timeout=None) | 該方法可用來與程序進行互動,比如傳送資料到stdin,從stdout和stderr讀取資料,直到到達檔案末尾。 |
Popen.send_signal(signal) | 傳送指定的訊號給這個子程序。 |
Popen.terminate() | 停止該子程序。 |
Popen.kill() | 殺死該子程序。 |
關於communicate()方法的說明:
- 該方法中的可選引數 input 應該是將被髮送給子程序的資料,或者如沒有資料傳送給子程序,該引數應該是None。input引數的資料型別必須是位元組串,如果universal_newlines引數值為True,則input引數的資料型別必須是字串。
- 該方法返回一個元組(stdout_data, stderr_data),這些資料將會是位元組穿或字串(如果universal_newlines的值為True)。
- 如果在timeout指定的秒數後該程序還沒有結束,將會丟擲一個TimeoutExpired異常。捕獲這個異常,然後重新嘗試通訊不會丟失任何輸出的資料。但是超時之後子程序並沒有被殺死,為了合理的清除相應的內容,一個好的應用應該手動殺死這個子程序來結束通訊。
- 需要注意的是,這裡讀取的資料是緩衝在記憶體中的,所以,如果資料大小非常大或者是無限的,就不應該使用這個方法。
3. subprocess.Popen使用例項
例項1:
>>> 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)
1
>>> print(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% /data2
>>> print(err)
None
四、總結
那麼我們到底該用哪個模組、哪個函式來執行命令與系統及系統進行互動呢?下面我們來做個總結:
- 首先應該知道的是,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類來實現我們需要的複雜功能。
問題交流群:666948590