【轉】python os.popen 超時問題


python 版本 2.5.4 (在高版本python中提倡使用 subprocess.Popen 取代 os.popen)

os.popen 會出現過長時間等待導致阻塞問題, 解決方法如下:

[python] view plain copy print?
def TIMEOUT_COMMAND(command, timeout):  
    """call shell-command and either return its output or kill it 
    if it doesn't normally exit within timeout seconds and return None"""  
    import subprocess, datetime, os, time, signal  
    cmd = command.split(" ")  
    start = datetime.datetime.now()  
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)  
    while process.poll() is None:  
        time.sleep(0.2)  
        now = datetime.datetime.now()  
        if (now - start).seconds> timeout:  
            os.kill(process.pid, signal.SIGKILL)  
            os.waitpid(-1, os.WNOHANG)  
            return None  
    return process.stdout.readlines()  

  

原文出自:http://blog.csdn.net/cenziboy/article/details/8298844


免責聲明!

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



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