咱們幾乎能夠在任何操做系統上經過命令行指令與操做系統進行交互,好比Linux平臺下的shell。那麼咱們如何經過Python來完成這些命令行指令的執行呢?另外,咱們應該知道的是命令行指令的執行一般有兩個咱們比較關注的結果:php
早期的Python版本中,咱們主要是經過os.system()、os.popen().read()等函數來執行命令行指令的,另外還有一個不多使用的commands模塊。可是從Python 2.4開始官方文檔中建議使用的是subprocess模塊,因此os模塊和commands模塊的相關函數在這裏只提供一個簡單的使用示例,咱們重要要介紹的是subprocess模塊。python
Python中提供瞭如下幾個函數來幫助咱們完成命令行指令的執行:git
函數名 | 描述 |
---|---|
os.system(command) | 返回命令執行狀態碼,而將命令執行結果輸出到屏幕 |
os.popen(command).read() | 能夠獲取命令執行結果,可是沒法獲取命令執行狀態碼 |
commands.getstatusoutput(command) | 返回一個元組(命令執行狀態碼, 命令執行結果) |
說明:shell
- os.popen(command)函數獲得的是一個文件對象,所以除了read()方法外還支持write()等方法,具體要根據command來定;
- commands模塊只存在於Python 2.7中,且不支持windows平臺,所以commands模塊不多被使用。另外,commands模塊實際上也是經過對os.popen()的封裝來完成的。
>>> 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 >>>
>>> 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 可用字節 >>>
須要注意的是commands模塊不支持windows平臺,所以該實例是在Linux平臺下執行的json
>>> 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模塊提供的屬性可知,它也提供了單獨獲取命令執行狀態碼和執行結果的函數,以下所示:windows
>>> dir(commands) ['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'getoutput', 'getstatus', 'getstatusoutput', 'mk2arg', 'mkarg']
subprocess是Python 2.4中新增的一個模塊,它容許你生成新的進程,鏈接到它們的 input/output/error 管道,並獲取它們的返回(狀態)碼。這個模塊的目的在於替換幾個舊的模塊和方法,如:api
函數 | 描述 |
---|---|
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平臺。
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)
須要說明的是,subprocess.run()函數是Python3.5中新增的一個高級函數,其返回值是一個subprocess.CompletedPorcess類的實例,所以,subprocess.completedPorcess類也是Python 3.5中才存在的。它表示的是一個已結束進程的狀態信息,它所包含的屬性以下:緩存
>>> 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(['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
>>> 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
>>> 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 桌面
>>> 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類提供的靈活的api來完成。安全
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=())
參數說明:
方法 | 描述 |
---|---|
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() | 殺死該子進程。 |
>>> 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
>>> 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)
>>> 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)
實現相似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
那麼咱們到底該用哪一個模塊、哪一個函數來執行命令與系統及系統進行交互呢?下面咱們來作個總結:
問題交流羣:666948590