This has probably been asked but I cannot find anything regarding a subprocess.call timeout when using python 2.7
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
A simple way I've always done timeouts with 2.7 is utilizing
subprocess.poll()
alongsidetime.sleep()
with a delay. Here's a very basic example:If you set
x = 600
, then your timeout would amount to 10 minutes. Whiletask.poll()
will query whether or not the process has terminated.time.sleep(delay)
will sleep for 1 second in this case, and then decrement the timeout by 1 second. You can play around with that part to your heart's content, but the basic concept is the same throughout.Hope this helps!
subprocess.poll()
https://docs.python.org/2/library/subprocess.html#popen-objectsIn python 3.3 timeout argument was added.
https://docs.python.org/3/library/subprocess.html#subprocess.call
You can try to use "easyprocess":
https://github.com/ponty/EasyProcess
It has many features that you need like "timeout".
You can use subprocess32 mentioned by @gps, which is backport of the subprocess standard library module from Python 3.2 - 3.5 for use on Python 2.
Firstly, install the subprocess32 module:
Here's a code snippet:
Notice, default
timeout=None
, which means never timeout.You could install
subprocess32
module mentioned by @gps -- the backport of thesubprocess
module from Python 3.2/3.3 for use on 2.x. It works on Python 2.7 and it includes timeout support from Python 3.3.subprocess.call()
is justPopen().wait()
and therefore to interrupt a long running process intimeout
seconds:If the child process may end sooner then a portable solution is to use
Timer()
as suggested in @sussudio's answer:On Unix, you could use
SIGALRM
as suggested in @Alex Martelli's answer:To avoid using threads and signals here,
subprocess
module on Python 3 uses a busy loop withwaitpid(WNOHANG)
calls on Unix andwinapi.WaitForSingleObject()
on Windows.