Python subprocess + timeout的命令執行


 

Popen對象

  • poll() 判斷是否執行完畢,執行完畢返回0,未執行完畢返回None
  • terminate() 終止進程發送SIGTERM信號
  • raise 自定義返回錯誤
import time  
import subprocess  
  
class TimeoutError(Exception):  
    pass  
  
def command(cmd, timeout=60):  
    """執行命令cmd,返回命令輸出的內容。 
    如果超時將會拋出TimeoutError異常。 
    cmd - 要執行的命令 
    timeout - 最長等待時間,單位:秒 
    """  
    p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)  
    t_beginning = time.time()  
    seconds_passed = 0  
    while True:  
        if p.poll() is not None:  
            break  
        seconds_passed = time.time() - t_beginning  
        if timeout and seconds_passed > timeout:  
            p.terminate()  
            raise TimeoutError(cmd, timeout)  
        time.sleep(0.1)  
    return p.stdout.read()  
  
if __name__ == "__main__":  
    print command(cmd='ping www.redicecn.com', timeout=1) 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM