简体   繁体   English

Python subprocess.call 超时重试

[英]Python subprocess.call with timeout retry

I want to re-run subprocess.call if it's timeout somehow.如果它以某种方式超时,我想重新运行 subprocess.call 。

subprocess.call('some command', timeout=600)
if timeout:
    subprocess.call('some command')

How do i do something like this?我该怎么做这样的事情?

subprocess.call raises [Python 3.Docs]: exception subprocess.TimeoutExpired when timeout is (given and) reached (just like Popen.communicate ). subprocess.call引发[Python 3.Docs]:异常 subprocess.TimeoutExpired当超时(给定和)达到(就像Popen.communicate )。

Here's a piece of code that keeps launching NotePad with a timeout of 3 seconds, until it runs 2 times, or user manually closes it:这是一段代码,它会以 3 秒的超时时间持续启动记事本,直到它运行 2 次,或者用户手动关闭它:

 >>> max_runs = 2 >>> run = 0 >>> while run < max_runs: ... try: ... subprocess.call("notepad", timeout=3) ... except subprocess.TimeoutExpired: ... continue ... else: ... break ... finally: ... run += 1 ... 0

Although this technically answers the question, I don't think it's a good idea to re-launch a process that didn't end, since there's a great chance that the consecutive runs will have the same outcome (will timeout).虽然这在技术上回答了这个问题,但我认为重新启动一个没有结束的进程并不是一个好主意,因为连续运行很有可能会产生相同的结果(将超时)。 In that case, you'd have to use Popen and communicate , and if the process times out, kill it via Popen.terminate .在这种情况下,您必须使用Popen通信,如果进程超时,请通过Popen.terminate将其终止。

You can use basic error handling to do catch the timeout exception:您可以使用基本错误处理来捕获超时异常:

try:
    subprocess.call('cmd', timeout=0)
except subprocess.TimeoutExpired:
    print('Expired!')
    # subprocess.call('cmd')

The except block is only run if the specified error is raised.只有在引发指定的错误时才会运行except块。 See Python docs tutorial on exceptions , specifically error handling for more information.有关更多信息,请参阅有关异常的 Python 文档教程,特别是错误处理

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

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