[英]Setting a timeout during a loop in Python?
So I'm running a loop through a directory where an external script, run by subprocess.Popen, is moving through the directory and performing calculations on each file. 因此,我正在一个目录中循环运行,该目录中有一个由subprocess.Popen运行的外部脚本在该目录中移动并在每个文件上执行计算。 The external script is a bit unstable and occasionally freezes when it runs into files that it doesn't know how to handle.
外部脚本有点不稳定,当它运行到不知道如何处理的文件中时,有时会冻结。 Is there a way to add a timeout function to subprocess.Popen so that I can skip over that file and move on to the next?
有没有一种方法可以向subprocess.Popen添加超时功能,这样我就可以跳过该文件并转到下一个文件?
EDIT: Here's my loop: 编辑:这是我的循环:
def automate():
os.chdir("/home/mlts/dir")
working_dir = b"/home/mts/dir"
for filename in os.listdir(working_dir):
if filename.endswith(".MTS"):
try:
print("Performing calculations on {filename!r}...".format(**vars()))
try:
os.remove("mts_tbl.txt")
except OSError:
pass
time.sleep(3)
p = Popen(["run_command.command", "-f", "a"], cwd=working_dir, stdin=PIPE)
p.communicate(input=b"\n".join([b"1", str(filename), b"8", b"alloy-liquid", b"0", b"x", b"5", b"4", b"-1.6", b"4", b"1", b"0"]))
To force timeout
on Python 2 (where .communicate(timeout=)
doesn't exist in stdlib), you could use threading.Timer()
: 要在Python 2上强制
timeout
(stdlib中不存在.communicate(timeout=)
),可以使用threading.Timer()
:
p = Popen(...)
t = Timer(3, p.kill) # kill in 3 seconds
t.start()
p.communicate(...)
t.cancel() # no need to kill, the process is dead already
The complete example: 完整的示例:
import os
import traceback
from glob import glob
from subprocess import Popen, PIPE
from threading import Timer
os.chdir("/home/mls/dir") #XXX assume mlts is a typo in the question
for filename in glob(b"*.MTS"):
print("Performing calculations on {filename!r}...".format(**vars()))
try:
os.remove("mts_tbl.txt")
except OSError:
pass # ignore
try:
p = Popen(["run_command.command", "-f", "a"], stdin=PIPE) #XXX no cwd
t = Timer(3, p.kill)
t.start()
p.communicate(input=b"\n".join([b"1", filename,
b"8\nalloy-liquid\n0\nx\n5\n4\n-1.6\n4\n1\n0"]))
t.cancel()
except Exception:
traceback.print_exc()
This code assumes that you want to run the child process in the current working directory of the parent Python script. 此代码假定您要在父Python脚本的当前工作目录中运行子进程。
On Python 3 or if subprocess32
is installed; 在Python 3上,或者是否安装了
subprocess32
; you could pass timeout
parameter to .communicate()
method instead of using Timer()
. 您可以将
timeout
参数传递给.communicate()
方法,而不是使用Timer()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.