python 進程超時控制 防止phantomjs假死

  • 2019 年 11 月 28 日
  • 筆記

目前的程式結構是一個主進程式控制制50個執行緒進行數據採集,採集的請求方式使用開進程調用phantomjs去發出帶瀏覽器處理能力的請求。

環境

linux  python 2.7

phantomjs

問題

phantomjs運作中卡死,導致調用其的執行緒長時間等待。

解決方案

用下程式碼將啟動phantomjs的進程用做超時設置

import subprocess  from threading import Timer  import time    kill = lambda process: process.kill()    cmd = ["ping", "www.google.com"]  ping = subprocess.Popen(      cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)    my_timer = Timer(5, kill, [ping])  try:      my_timer.start()      stdout, stderr = ping.communicate()      #print stdout      print time.ctime()  finally:      print time.ctime()      my_timer.cancel()

原創文章,轉載請註明: 轉載自URl-team