python重要模組之subprocess模組

來源:互聯網
上載者:User

標籤:pipe   dir   地址   推出   eth   主程   代碼執行   python3.6   ssi   

python重要模組之subprocess模組

我們經常要通過python去執行系統的命令或者指令碼,系統的shell命令是獨立於你的python進程之外的,每執行一條命令,就相當於發起了一個新的進程,通過python調用系統命令或指令碼的模組。

之前我們也學到過和系統互動的模組-os模組

In [1]: import osIn [2]: os.system(‘uname -a‘)Linux host-10-200-137-195 3.10.0-693.21.1.el7.x86_64 #1 SMP Wed Mar 7 19:03:37 UTC 2018 x86_64 x86_64 x86_64 GNU/LinuxOut[2]: 0  # 命令的執行返回結果,0為執行成功,非0表示失敗

除了so.system可以調用系統命令,commands和popen2等也可以,因為比較亂,所以官方推出了subprocess,目的就是提供統一的模組來實現對系統命令或指令碼的調用。簡單示範下commands的用法:
commands模組講解

# commands模組,在python2中運行>>> import commands  # 匯入這個模組>>> status,output = commands.getstatusoutput(‘ls‘)  >>> status  # 代表shell命令的返回狀態0>>> output  # 代表shell命令你的執行結果‘anaconda-ks.cfg‘
三種命令的執行方式
  • subprocess.run() # 官方推薦
  • subprocess.call() # 跟run()方法差不多,另一種寫法
  • subprocess.Popen() # 上面各種方法的封裝
run()方法

標準寫法

subprocess.run([‘df‘,‘-h‘],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True)

慢慢來講:

In [2]: subprocess.run([‘df‘,‘-h‘])  # 這個是將shell命令拆分成列表的形式寫Filesystem               Size  Used Avail Use% Mounted on/dev/mapper/centos-root   50G  2.2G   48G   5% /devtmpfs                 3.9G     0  3.9G   0% /devtmpfs                    3.9G     0  3.9G   0% /dev/shmtmpfs                    3.9G  8.4M  3.9G   1% /runtmpfs                    3.9G     0  3.9G   0% /sys/fs/cgroup/dev/vda1                509M  175M  335M  35% /boottmpfs                    783M     0  783M   0% /run/user/0Out[2]: CompletedProcess(args=[‘df‘, ‘-h‘], returncode=0)  # 返回了一個對象# 賦值a = subprocess.run([‘df‘,‘-h‘])  # 此時a就是返回的那個對象,通過這個對象,我們可以使用很多方法In [3]: a  # 就是返回的那個對象Out[3]: CompletedProcess(args=[‘df‘, ‘-h‘], returncode=0)In [4]: a.returncode  # 查看shell命令執行狀態Out[4]: 0In [5]: a.args  # 查看所帶的參數Out[5]: [‘df‘, ‘-h‘]In [6]: a.check_returncode  # 判斷命令執行狀態是否為0,不為0則報錯Out[6]: <bound method CompletedProcess.check_returncode of CompletedProcess(args=[‘df‘, ‘-h‘], returncode=0)>In [7]: a.stdoutIn [8]: a.stderr

那麼問題來了,為什麼a.stdout和a.stderr沒有輸出任何東西呢?讓我們來看看subprocess模組內部的工作機制吧?

通過python去執行Liunx命令,相當於發起了一個新的進程,我們比如: 在Word文檔中把QQ開啟了,word要佔用記憶體,QQ也要佔用記憶體,那麼在word中能不能給QQ裡的好友發送訊息呢?
答案是不能的,因為:如果wold可以去訪問QQ的記憶體資料,那麼就可以通過QQ發送資料了,那麼就會有一個問題出現,QQ被搞崩了,所以作業系統為了避免這樣的事情發生,就嚴格的限制了每個進程在記憶體中都是獨立的,我們再打個比方:在瀏覽器中複製粘貼,其實就是通過作業系統去實現的,作業系統也有著自己的記憶體,從瀏覽器中賦值的內容,然後通過作業系統導給QQ等,作業系統可以訪問每個進程的記憶體。
python和shell的關係就是這樣,subprocess幫我們發起了一個進程然後得到結果,python和shell之間是不互連的,如果想要互連,那麼就需要有個橋樑,即python和作業系統之間的橋樑。
所以就會有這麼一種寫法了

subprocess.run([ls‘‘,‘-l‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE)其中PIPE就相當於是橋樑,stdout和stderr被稱為標準輸出# 此時讓我們再看一下運行結果In [9]: a = subprocess.run([‘ls‘,‘-l‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE)In [10]: a.stdout  # 標準輸出Out[10]: b‘total 4\n-rw-------. 1 root root 1224 Oct 15  2016 anaconda-ks.cfg\n‘In [11]: a.stderr  # 標準錯誤輸出Out[11]: b‘‘

繼續往下講,在run()方法中,check=True是啥意思呢?寫代碼看下:

In [13]: a = subprocess.run([‘ls‘,‘-ldada‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE,check=True)  # 故意設定shell命令是錯誤的,結果並不檢查    ...: In [14]: a = subprocess.run([‘ls‘,‘-lkjh‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE,check=True)  # 檢查shell命令是否正確,不正確則報錯---------------------------------------------------------------------------CalledProcessError                        Traceback (most recent call last)<ipython-input-14-0e63d8200326> in <module>()----> 1 a = subprocess.run([‘ls‘,‘-lkjh‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE,check=True)/usr/local/lib/python3.6/subprocess.py in run(input, timeout, check, *popenargs, **kwargs)    416         if check and retcode:    417             raise CalledProcessError(retcode, process.args,--> 418                                      output=stdout, stderr=stderr)    419     return CompletedProcess(process.args, retcode, stdout, stderr)    420 CalledProcessError: Command ‘[‘ls‘, ‘-lkjh‘]‘ returned non-zero exit status 2.In [15]: a = subprocess.run([‘ls‘,‘-lkjh‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE)In [16]: a = subprocess.run([‘ls‘,‘-lkjh‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE),check=True  File "<ipython-input-16-15adea8e8d2f>", line 1    a = subprocess.run([‘ls‘,‘-lkjh‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE),check=True       ^SyntaxError: can‘t assign to function call

如果想執行複雜的shell命令,讓我們來看看怎麼寫?

In [17]: a = subprocess.run([‘df‘,‘-h‘,‘|‘,‘grep‘,‘Used‘],stdout=subprocess.PIPE,stderr=subprocess.PI    ...: PE)  # 剛剛的ls -l不就是這樣的嘛一直拼參數怎麼會報錯了呢In [18]: a.stderr  # 我知道是錯誤的,故意直接寫的是標準錯誤輸出Out[18]: b‘df: \xe2\x80\x98|\xe2\x80\x99: No such file or directory\ndf: \xe2\x80\x98grep\xe2\x80\x99: No such file or directory\ndf: \xe2\x80\x98Used\xe2\x80\x99: No such file or directory\n‘# 其實應該這樣寫In [21]: a = subprocess.run(‘df -h | grep Used‘,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)In [22]: a.stdoutOut[22]: b‘Filesystem               Size  Used Avail Use% Mounted on\n‘In [23]: a.stderrOut[23]: b‘‘# shell=True這樣寫就是告訴subprocess,你之前幫我拼參數,但是現在不用了,只需要把整條命令傳遞個shell去處理就行了
call()方法

廢話不多說,直接看代碼

In [24]: subprocess.call([‘ls‘,‘-l‘])total 4-rw-------. 1 root root 1224 Oct 15  2016 anaconda-ks.cfgOut[24]: 0  # 命令執行的返回狀態,0代表成功# 執行命令,如果命令結果為0,就正常返回,否則拋異常In [25]: subprocess.check_call([‘ls‘,‘-l‘])total 4-rw-------. 1 root root 1224 Oct 15  2016 anaconda-ks.cfgOut[25]: 0In [26]: subprocess.check_call([‘ls‘,‘-lhgj‘])ls: invalid option -- ‘j‘Try ‘ls --help‘ for more information.---------------------------------------------------------------------------CalledProcessError                        Traceback (most recent call last)<ipython-input-26-c38033ac38dc> in <module>()----> 1 subprocess.check_call([‘ls‘,‘-lhgj‘])/usr/local/lib/python3.6/subprocess.py in check_call(*popenargs, **kwargs)    289         if cmd is None:    290             cmd = popenargs[0]--> 291         raise CalledProcessError(retcode, cmd)    292     return 0    293 CalledProcessError: Command ‘[‘ls‘, ‘-lhgj‘]‘ returned non-zero exit status 2.# 接受字串格式的命令,返回元組形式,第1個元素是執行狀態,第2個是命令結果In [27]: subprocess.getstatusoutput(‘ls /bin/ls‘)Out[27]: (0, ‘/bin/ls‘)# 接收字串格式命令,並返回結果In [29]: subprocess.getoutput(‘df -h | grep Used‘)Out[29]: ‘Filesystem               Size  Used Avail Use% Mounted on‘# 執行命令並返回結果,注意是返回結果,不是列印,
Popen()方法

常用參數

  • args:shell命令,可以是字元或者序列化類別型(list,tuple)
  • stdint,stdout,stderr:分別表示程式的標準輸入、輸出、錯誤
  • preexec_fn:只在Unix平台下有效,用於指定一個可執行對象,它將在子進程運行之前被調用
  • shell:同上
  • cwd:用於指定子進程的目前的目錄
  • env:用於指定子進程的環境變數,如果env=None,子進程的環境變數將會從父進程中繼承

下面這兩條語句執行會有什麼區別?

In [7]: a = subprocess.call(‘sleep 10‘,shell=True,stdout=subprocess.PIPE)  # 它會一直等待著這段代碼執行完才結束In [8]: a = subprocess.Popen(‘sleep 10‘,shell=True,stdout=subprocess.PIPE)  # 相當於是有兩個進程,主程式繼續下一步行動,其餘則另開一個新的進程執行sleep 10

如果你調用的命令或指令碼需要哦執行10分鐘,你的主程式不需卡在哪裡等待10分鐘,可以繼續往下走幹別的事情,每過一會,就可以通過poll()方法去檢測一下這個命令是否執行完成。
Popen調用後會返回一個對象,可以通過這個對象拿到命令的執行結果或狀態等,該對象有以下方法:
1.poll():查看這個進程的執行狀態,沒有執行完則不輸出,執行正確輸出0,錯誤非0

In [13]: a = subprocess.Popen(‘sleep 10‘,shell=True,stdout=subprocess.PIPE)In [14]: a.poll()

2.wait():等待這個進程結束,知道返回運行結果

In [15]: a = subprocess.Popen(‘sleep 10‘,shell=True,stdout=subprocess.PIPE)In [16]: a.wait()Out[16]: 0

3.terminate():終止所啟動的進程
4.kill():殺死所啟動的進程

In [24]: a = subprocess.Popen(‘for i in $(seq 1 100);do sleep 1;echo $i >> sleep1.log;done‘,shell=True,stdou    ...: t=subprocess.PIPE)In [25]: a.terminate  # 這個是記憶體位址Out[25]: <bound method Popen.terminate of <subprocess.Popen object at 0x7f49d85717f0>>In [26]: a.terminate()  # 殺死進程的一種方法In [28]: a = subprocess.Popen(‘for i in $(seq 1 100);do sleep 1;echo $i >> sleep1.log;done‘,shell=True,stdou    ...: t=subprocess.PIPE)In [29]: a.kill()  # 殺死進程的另一種方法

5.pid():擷取子進程的pid

In [30]: a = subprocess.Popen(‘for i in $(seq 1 100);do sleep 1;echo $i >> sleep1.log;done‘,shell=True,stdou    ...: t=subprocess.PIPE)In [33]: a.pidOut[33]: 4931

現在講一下Popen方法的其中幾個參數

# cwd設定子進程的目前的目錄In [4]: a = subprocess.Popen(‘echo $PWD;sleep 2‘,shell=True,cwd=‘/tmp‘,stdout=subprocess.PIPE)In [5]: a.stdout.read()Out[5]: b‘/tmp\n‘# preexec_fn=  在子進程運行之前被調用# 最後一個,與程式的互動,communicate(),發送資料到stdin,並從stdout接收輸入,然後等待任務結束這是一個猜數位遊戲1.py 11 import random 12       13 num = random.randint(1,100) 14 your_guess = int(input(‘your_guess:‘)) 15       16 if your_guess > num: 17     print(‘bigger‘) 18 elif yur_guess < num: 19     print(‘smaller‘) 20 else: 21     print(‘ok‘)   程式互動:>>> import subprocess>>> a = subprocess.Popen(‘python3 1.py‘,shell=True,stdout=subprocess.PIPE)然後:a.communicate(b‘22‘)  # 就可以了,我的xshell一運行就中斷連線,所以,我就不示範啦。

python重要模組之subprocess模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.