#!/usr/bin/env python # -*- coding:utf-8 -*- # author: Changhua Gong import subprocess ''' 1. 推薦使用subprocess模塊代替其餘模塊執行shell命令; 2. call不管是否正確執行都會返回returncode attribute,即便執行命令報錯了,後面的語句會繼續執行, check_call & check_output執行命令報錯後(returncode非0)直接拋出CalledProcessError,後續命令再也不執行, 可以使用try...except...捕捉; 3. call不管是否正確執行都會返回returncode attribute,即便執行命令報錯了,後面的語句會繼續執行; 4. check_call:Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. check_call要麼返回0,要麼直接拋出異常CalledProcessError,異常對象裏僅有returncode; 5. check_output:Run command with arguments and return its output. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. check_output要麼返回直接返回命令運行結果(returncode爲0,命令正確執行), 要麼直接拋出異常CalledProcessError,異常對象裏有returncode和output; ''' rs = subprocess.call([ "ipconfig" , "/all" ]) print ( "Exit code: " , rs) # 執行後的返回結果 try : rs = subprocess.check_call([ "dir" , "c:" ]) print ( "Exit code: " , rs) # 執行後的返回結果 except Exception as e: print (e) print ( "........................................" ) try : rs = subprocess.check_output([ "dir" , "c:" ], stderr =subprocess.STDOUT) print ( "Exit code: " , rs) # 執行後的返回結果 except Exception as e: print (e) print ( "........................................" ) '''如下命令在linux上嘗試''' import subprocess rs = subprocess.call( "ls -l hellokity" , shell = True ) print ( "Exit code: " , rs) # 執行後的返回結果 try : rs = subprocess.check_call( "ls -l hellokity" , shell = True ) except subprocess.CalledProcessError as e: print (e.returncode) try : rs = subprocess.check_output( "ls -l hellokity" , shell = True , stderr =subprocess.STDOUT) except subprocess.CalledProcessError as e: out_bytes = e.output.decode() # Output generated before error,這裏需指定stderr=subprocess.STDOUT,報錯後纔有內容返回 code = e.returncode # Return code print (out_bytes, code) '''Popen的交互 Popen對象建立後,主程序不會自動等待子進程完成。咱們必須調用對象的wait()方法,父進程纔會等待 communicate()是Popen對象的一個方法,該方法會阻塞父進程,直到子進程完成。 ''' child1 = subprocess.Popen([ "ls" , "-l" ], stdout =subprocess.PIPE) child2 = subprocess.Popen([ "wc" , "-l" ], stdin =child1.stdout, stdout =subprocess.PIPE) stdout, stderr = child2.communicate() # 負責交互 print (stdout.decode(), stderr) text = b''' abc 123 xya sda ''' child = subprocess.Popen([ "wc" , "-l" ], stdin =subprocess.PIPE, stdout =subprocess.PIPE) # child.wait() #若是是調用了communicate,則不需使用wait,由於communicate自動等待子進程結束 stdout, stderr = child.communicate(text) # 負責交互 print (stdout.decode(), stderr)