Python模組-subprocess模組

來源:互聯網
上載者:User

標籤:sda   返回結果   use   help   否則   ash   oam   元素   gets   

Run()方法
>>> a = subprocess.run([‘df‘,‘-h‘])檔案系統        容量  已用  可用 已用% 掛載點udev            468M     0  468M    0% /devtmpfs            98M  7.4M   91M    8% /run/dev/sda1        39G  5.0G   32G   14% /tmpfs           488M  216K  488M    1% /dev/shmtmpfs           5.0M  4.0K  5.0M    1% /run/locktmpfs           488M     0  488M    0% /sys/fs/cgrouptmpfs            98M   84K   98M    1% /run/user/1000>>> aCompletedProcess(args=[‘df‘, ‘-h‘], returncode=0)>>> a.returncode  # 擷取命令執行結果的狀態代碼0>>> a.args  # 擷取命令參數列表[‘df‘, ‘-h‘]

 直接把命令按照列表傳入

 如果想要讀取命令執行的結果和錯誤,需要通過管道

>>> a = subprocess.run([‘df‘,‘-h‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE)>>> a.stdout  # 如果命令執行成功就能讀出執行結果b‘\xe6\x96\x87\xe4\xbb\xb6\xe7\xb3\xbb\xe7\xbb\x9f        \xe5\xae\xb9\xe9\x87\x8f  \xe5\xb7\xb2\xe7\x94\xa8  \xe5\x8f\xaf\xe7\x94\xa8 \xe5\xb7\xb2\xe7\x94\xa8% \xe6\x8c\x82\xe8\xbd\xbd\xe7\x82\xb9\nudev            468M     0  468M    0% /dev\ntmpfs            98M  7.4M   91M    8% /run\n/dev/sda1        39G  5.0G   32G   14% /\ntmpfs           488M  216K  488M    1% /dev/shm\ntmpfs           5.0M  4.0K  5.0M    1% /run/lock\ntmpfs           488M     0  488M    0% /sys/fs/cgroup\ntmpfs            98M   84K   98M    1% /run/user/1000\n‘>>> a.stdout.decode()‘檔案系統        容量  已用  可用 已用% 掛載點\nudev            468M     0  468M    0% /dev\ntmpfs            98M  7.4M   91M    8% /run\n/dev/sda1        39G  5.0G   32G   14% /\ntmpfs           488M  216K  488M    1% /dev/shm\ntmpfs           5.0M  4.0K  5.0M    1% /run/lock\ntmpfs           488M     0  488M    0% /sys/fs/cgroup\ntmpfs            98M   84K   98M    1% /run/user/1000\n‘>>> a.stderr  # 如果命令執行成功,讀取的錯誤就為空白b‘‘>>> a = subprocess.run([‘df‘,‘-asdh‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE)>>> a.stdout.decode()  # 如果命令執行錯誤,讀出來的執行結果就為空白‘‘>>> a.stderr  # 如果命令執行錯誤,就能讀出錯誤的內容b"df\xef\xbc\x9a\xe6\x97\xa0\xe6\x95\x88\xe9\x80\x89\xe9\xa1\xb9 -- s\nTry ‘df --help‘ for more information.\n">>> a.stderr.decode()"df:無效選項 -- s\nTry ‘df --help‘ for more information.\n"

 stdout=subprocess.PIPE為命令執行成功返回的內容

 stderr=subprocess.PIPE為命令執行錯誤返回的錯誤內容

 因為執行一條命令就會開啟一個進程,進程間資料不能通訊,所以作業系統對stdout、stderr的結果進行讀取,再傳給程式

 subprocess.run()方法執行命令時,如果命令是錯的,程式不會報錯而繼續運行,如果要命令錯的時候程式報錯停止啟動並執行話,可以加個check參數

 check參數設定為True的時候就會檢查命令是否是錯的

>>> a = subprocess.run([‘df‘,‘-asdh‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE)>>> a.stderr.decode()"df:無效選項 -- s\nTry ‘df --help‘ for more information.\n">>> a = subprocess.run([‘df‘,‘-asdh‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE,check=True)Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "/usr/lib/python3.5/subprocess.py", line 708, in run    output=stdout, stderr=stderr)subprocess.CalledProcessError: Command ‘[‘df‘, ‘-asdh‘]‘ returned non-zero exit status 1

 執行帶有管道符的命令

>>> a = subprocess.run(‘df -h |grep sda1‘,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)>>> aCompletedProcess(args=‘df -h |grep sda1‘, returncode=0, stdout=b‘/dev/sda1        39G  5.0G   32G   14% /\n‘, stderr=b‘‘)
Call()方法

 執行命令,返回命令執行狀態

>>> retcode = subprocess.call([‘df‘, ‘-h‘])檔案系統        容量  已用  可用 已用% 掛載點udev            468M     0  468M    0% /devtmpfs            98M  7.4M   91M    8% /run/dev/sda1        39G  5.0G   32G   14% /tmpfs           488M  216K  488M    1% /dev/shmtmpfs           5.0M  4.0K  5.0M    1% /run/locktmpfs           488M     0  488M    0% /sys/fs/cgrouptmpfs            98M   84K   98M    1% /run/user/1000>>> retcode0

 執行命令,如果命令執行狀態為0,就正常返回,否則拋異常

>>> subprocess.check_call([‘df‘, ‘-h‘])檔案系統        容量  已用  可用 已用% 掛載點udev            468M     0  468M    0% /devtmpfs            98M  7.4M   91M    8% /run/dev/sda1        39G  5.0G   32G   14% /tmpfs           488M  216K  488M    1% /dev/shmtmpfs           5.0M  4.0K  5.0M    1% /run/locktmpfs           488M     0  488M    0% /sys/fs/cgrouptmpfs            98M   84K   98M    1% /run/user/10000>>> subprocess.check_call([‘df‘, ‘-ash‘])df:無效選項 -- sTry ‘df --help‘ for more information.Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "/usr/lib/python3.5/subprocess.py", line 581, in check_call    raise CalledProcessError(retcode, cmd)subprocess.CalledProcessError: Command ‘[‘df‘, ‘-ash‘]‘ returned non-zero exit status 1

 接收字串格式命令,返回元組形式,第1個元素是執行狀態,第2個是命令結果

>>> subprocess.getstatusoutput(‘whoami‘)(0, ‘sch01ar‘)

 接收字串格式命令,並返回結果

>>> subprocess.getoutput(‘whoami‘)‘sch01ar‘

 執行命令,並返回結果

>>> subprocess.check_output([‘df‘,‘-h‘]).decode()‘檔案系統        容量  已用  可用 已用% 掛載點\nudev            468M     0  468M    0% /dev\ntmpfs            98M  7.4M   91M    8% /run\n/dev/sda1        39G  5.0G   32G   14% /\ntmpfs           488M  216K  488M    1% /dev/shm\ntmpfs           5.0M  4.0K  5.0M    1% /run/lock\ntmpfs           488M     0  488M    0% /sys/fs/cgroup\ntmpfs            98M   84K   98M    1% /run/user/1000\n‘>>> a = subprocess.check_output([‘df‘,‘-h‘]).decode()>>> a‘檔案系統        容量  已用  可用 已用% 掛載點\nudev            468M     0  468M    0% /dev\ntmpfs            98M  7.4M   91M    8% /run\n/dev/sda1        39G  5.0G   32G   14% /\ntmpfs           488M  216K  488M    1% /dev/shm\ntmpfs           5.0M  4.0K  5.0M    1% /run/lock\ntmpfs           488M     0  488M    0% /sys/fs/cgroup\ntmpfs            98M   84K   98M    1% /run/user/1000\n‘
Popen()方法

popen()方法執行命令的進程和主程式的進程為並行

>>> subprocess.run([‘sleep‘,‘10‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE)CompletedProcess(args=[‘sleep‘, ‘10‘], returncode=0, stdout=b‘‘, stderr=b‘‘)>>> subprocess.Popen([‘sleep‘,‘10‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE)<subprocess.Popen object at 0x7f7fe17adda0>

 subprocess.run()睡眠10秒之後才返回,subprocess.Popen()直接返回

>>> a = subprocess.Popen([‘sleep‘,‘10‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE)>>> a.wait()0

 wait()會等待進程結束

>>> a = subprocess.Popen([‘whoami‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE)>>> a.stdout.read()  # 讀取命令執行成功的結果b‘sch01ar\n‘>>> a.stderr.read()  # 讀取命令執行錯誤的結果b‘‘>>> a.poll()  #檢查子進程是否已終止,返回傳回值0>>> a.args  # 返回命令參數[‘whoami‘]>>> a.pid  # 返回當前命令的進程號24999>>> a.returncode  # 返回傳回值0

 terminate():給系統發訊號,終止所啟動的進程,不一定會終止

 kill():殺死所啟動的進程

 communicate():與啟動的進程互動,發送資料到stdin,並從stdout接收輸出,然後等待任務結束

>>> a = subprocess.Popen([‘python3‘,‘test.py‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE)>>> a.communicate(‘sch01ar‘)(b"a\x7fa.cco\t‘ch01ar‘)\n", b‘‘)

 communicate()只能與啟動的進程互動一次

 send_signal():發送系統訊號

>>> a = subprocess.Popen([‘sleep‘,‘30‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE)>>> a.send_signal(signal.SIGKILL)

 preexec_fn:只在Unix平台下有效,用於指定一個函數,它將在子進程運行之前被調用

>>> def test():...    print(‘This is a test‘)... >>> a = subprocess.Popen([‘whoami‘],stdout=subprocess.PIPE,stderr=subprocess.PIPE,preexec_fn=test)>>> a.stdout.read()b‘This is a test\nsch01ar\n‘

 cwd:用於設定子進程的目前的目錄

>>> a = subprocess.Popen(‘echo $PWD‘,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)>>> a.stdout.read()b‘/home/sch01ar\n‘>>> a = subprocess.Popen(‘echo $PWD‘,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,cwd=‘/home/sch01ar/Desktop/‘)>>> a.stdout.read()b‘/home/sch01ar/Desktop\n‘

 shell的作用跟subprocess.run()方法中的shell作用一樣

 env:用於指定子進程的環境變數。如果env = None,子進程的環境變數將從父進程中繼承

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.