set timeout for a shell command in python

以下就是python調用系統命令設置超時:
  1. def TIMEOUT_COMMAND( command, timeout) :
  2.     "" "call shell-command and either return its output or kill it
  3.     if it doesn't normally exit within timeout seconds and return None" ""
  4.     import subprocess , datetime , os , time , signal
  5.     cmd = command.split ( " " )
  6.     start = datetime .datetime .now ( )
  7.     process = subprocess .Popen ( cmd , stdout=subprocess .PIPE , stderr=subprocess .PIPE )
  8.     while process.poll ( ) is None :
  9.         time .sleep ( 0 .2 )
  10.         now = datetime .datetime .now ( )
  11.         if ( now - start) .seconds > timeout:
  12.             os .kill ( process.pid , signal .SIGKILL )
  13.             os .waitpid ( -1 , os .WNOHANG )
  14.             return None
  15.     return process.stdout .readlines ( )
  16. print TIMEOUT_COMMAND(['ping','192.168.0.254'], 3)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章