Skip to content

Commit 01c28e3

Browse files
committed
timeout argument in subprocess for Python 3.2-.
1 parent 15e00a5 commit 01c28e3

1 file changed

Lines changed: 40 additions & 4 deletions

File tree

‎language_tool/__init__.py‎

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,42 @@
6060
cache = {}
6161

6262

63+
# For Python 3.2-
64+
try:
65+
subprocess.TimeoutExpired #@UndefinedVariable
66+
except AttributeError:
67+
import time
68+
69+
class TimeoutExpired(Exception):
70+
"""Raised when the timeout expires while waiting for a child process.
71+
"""
72+
73+
def Popen_wait(self, timeout=None):
74+
"""Wait for child process to terminate.
75+
"""
76+
if timeout is None:
77+
return _Popen_wait(self)
78+
deadline = time.time() + timeout
79+
while self.poll() is None:
80+
if time.time() > deadline:
81+
raise TimeoutExpired
82+
time.sleep(0.01)
83+
return self.returncode
84+
85+
def Popen_communicate(self, input=None, timeout=None): #@ReservedAssignment
86+
"""Interact with process.
87+
"""
88+
if timeout is not None:
89+
self.wait(timeout)
90+
return _Popen_communicate(self, input)
91+
92+
_Popen_wait = subprocess.Popen.wait
93+
_Popen_communicate = subprocess.Popen.communicate
94+
subprocess.Popen.wait = Popen_wait
95+
subprocess.Popen.communicate = Popen_communicate
96+
subprocess.TimeoutExpired = TimeoutExpired
97+
98+
6399
class Error(Exception):
64100
"""LanguageTool Error
65101
"""
@@ -215,7 +251,7 @@ def _start_server(cls):
215251
params = {"language": FAILSAFE_LANGUAGE, "text": ""}
216252
data = urllib.parse.urlencode(params).encode()
217253
try:
218-
with urlopen(cls.url, data, 15) as f:
254+
with urlopen(cls.url, data, cls.TIMEOUT) as f:
219255
tree = ElementTree.parse(f)
220256
except (IOError, http.client.HTTPException) as e:
221257
raise ServerError("{}: {}".format(cls.url, e))
@@ -345,7 +381,7 @@ def get_version():
345381
universal_newlines=True,
346382
startupinfo=startupinfo
347383
)
348-
out = proc.communicate("")[0]
384+
out = proc.communicate("", LanguageTool.TIMEOUT)[0]
349385
match = version_re.search(out)
350386

351387
if not match:
@@ -363,11 +399,11 @@ def get_version_info():
363399
VersionInfo = namedtuple("VersionInfo",
364400
("major", "minor", "micro", "releaselevel"))
365401
info_list = get_version().split("-")
366-
release_level = "final" if len(info_list) < 2 else info_list[-1]
402+
releaselevel = "final" if len(info_list) < 2 else info_list[-1]
367403
info_list = [int(e) if e.isdigit() else e
368404
for e in info_list[0].split(".")][:3]
369405
info_list += [0] * (3 - len(info_list))
370-
return VersionInfo(*info_list, release_level=release_level)
406+
return VersionInfo(*info_list, releaselevel=releaselevel)
371407

372408

373409
def get_languages():

0 commit comments

Comments
 (0)