繁体   English   中英

如何检测是否已达到Python子进程的超时时间?

[英]How can I detect whether the timeout in Python's subprocess has been reached?

我想区分失败的流程和超时的流程。 Python 确实捕获了错误并清楚地标识了它。 很好,但是没有雪茄,因为我想写自己的与超时错误相对应的日志消息。 有关当前的实现以及对所需内容的说明,请参见下文。

如果程序是这样的:

#!/usr/bin/env python3

"""
My job is to demonstrate a problem detecting timeout failures. 
"""

import os
import sys
import logging
import subprocess
import time

# Create main (root) logging object
logger = logging.getLogger('{}'.format(__file__))
logger.setLevel(logging.DEBUG)

# Formatter
consoleh = logging.StreamHandler(sys.stdout)
consoleh.setLevel(logging.INFO)
console_formatter = logging.Formatter('%(asctime)s   %(name)s   PID: %(process)d   TID: %(thread)d   %(levelname)s \n ==> %(message)s',datefmt='%Y-%m-%d at %H:%M:%S.%s')
consoleh.setFormatter(console_formatter)
logger.addHandler(consoleh)

def preHook(script):
  logger.debug('preHook called.')
  command = "{}".format(script)
  logger.info('preHook Executing with 15 second timeout: \n     /bin/sh -c {}'.format(command))
  process = subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)# timeout in seconds
  process.wait(timeout=15)
  proc_stdout, proc_stderr = process.communicate()
  if process.returncode == 0:
    logger.info('preHook: Process complete: \n     Command: /bin/sh -c {}\n     STDOUT: "{}"\n     STDERR: "{}"\n     Exit Code: {}\n     at: {}'.format(command,proc_stdout.decode('utf8').strip(),proc_stderr.decode('utf8').strip(),process.returncode,time.time()))
  else:
    exitcode = 1
    logger.error('preHook: Process failed: \n     Command: /bin/sh -c {}\n     STDOUT: "{}"\n     STDERR: "{}"\n     Exit Code: {}\n     at: {}'.format(command,proc_stdout.decode('utf8').strip(), proc_stderr.decode('utf8').strip(),process.returncode,time.time()))

def main():
  preHook('find -type f')

if __name__ == "__main__":
  main()

如何捕获超时错误并在标准错误输出中写入相关消息?

控制台输出

Python的子进程包清楚地捕获了超时错误。

2017-08-28 at 09:44:57.1503906297   detecttimeout.py   PID: 16915   TID: 140534594959104   INFO
 ==> preHook Executing with 15 second timeout:
     /bin/sh -c find -type f
Traceback (most recent call last):
  File "detecttimeout.py", line 40, in <module>
    main()
  File "detecttimeout.py", line 37, in main
    preHook('find -type f')
  File "detecttimeout.py", line 28, in preHook
    process.wait(timeout=15)
  File "/home/USER/devel/python/Python-3.4.5/Lib/subprocess.py", line 1561, in wait
    raise TimeoutExpired(self.args, timeout)
subprocess.TimeoutExpired: Command 'find -type f' timed out after 15 seconds

我想像处理失败一样赶上超时。 为了实现捕获失败的进程,我使用逻辑中所示的返回码。 消息preHook: Process failed... preHook: Process timed out...一条消息: preHook: Process timed out...

抓住错误

try:
  process.wait(timeout=15)
except subprocess.TimeoutExpired as e:
  logger.error(e) #logs the default error from subprocess.TimeoutExpired
  logger.error("Boom")
  return

编辑:更准确,并记录错误消息

您可以更换

process.wait(timeout=15)

通过

try:
    process.wait(timeout=15)
except subprocess.TimeoutExpired:
    logger.error(<your error message>)
    return

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM