當我們在寫執行一個命令或者一個函數的時候,處理的時間太長或者卡死在某個位置時,我們想要中斷,就需要進行一定的處理。廢話不多說,上代碼,自己看。
def set_command_exec_timeout(cmd_string):
'''
設置命令執行超時
:param cmd_string: 執行的命令
:return:
'''
class TimeoutException(Exception):pass
@contextmanager
def time_limit(seconds):
def signal_handler(signum, frame):
raise TimeoutException, "Timed out!"
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
def function():
p = subprocess.Popen(cmd_string, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
cmd_out_info = p.stdout.readlines()
p.terminate()
return cmd_out_info
try:
with time_limit(1):
return function()
except TimeoutException as e:
print "Time out!"
return
參考鏈接:https://www.cnblogs.com/buxizhizhoum/p/7113355.html