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

时间:2017-08-28 07:49:37

标签: python subprocess

我想区分失败的流程和超时流程。 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' subprocess包清楚地捕获超时错误。

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...

2 个答案:

答案 0 :(得分:1)

抓住错误

package First_test;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class first_case {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        // Create a new instance of the Firefox driver
                WebDriver driver = new FirefoxDriver();

                //Launch the Website
                driver.get("http://127.0.0.1:3000");

                // Print a Log In message to the screen
                System.out.println("Successfully opened the website ");


                // Close the driver
                driver.quit();

    }

}

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

答案 1 :(得分:1)

您可以替换

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)