Skip to content

Commit 5058e6d

Browse files
committed
bpc-29877: compileall: import ProcessPoolExecutor only when needed
Importing ProcessPoolExecutor may hang or cause an error when the import accesses urandom on a low resource platform
1 parent b5fd9ad commit 5058e6d

File tree

2 files changed

+17
-8
lines changed

2 files changed

+17
-8
lines changed

Lib/compileall.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,9 @@
1616
import py_compile
1717
import struct
1818

19-
try:
20-
from concurrent.futures import ProcessPoolExecutor
21-
except ImportError:
22-
ProcessPoolExecutor = None
19+
# Only import when needed, as low resource platforms may fail to import it
20+
ProcessPoolExecutor = None
21+
2322
from functools import partial
2423

2524
__all__ = ["compile_dir","compile_file","compile_path"]
@@ -70,13 +69,21 @@ def compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None,
7069
workers: maximum number of parallel workers
7170
invalidation_mode: how the up-to-dateness of the pyc will be checked
7271
"""
73-
if workers is not None and workers < 0:
74-
raise ValueError('workers must be greater or equal to 0')
75-
72+
global ProcessPoolExecutor
73+
if workers is not None:
74+
if workers < 0:
75+
raise ValueError('workers must be greater or equal to 0')
76+
elif workers > 1 and ProcessPoolExecutor is None:
77+
try:
78+
from concurrent.futures import ProcessPoolExecutor as PPE
79+
except ImportError:
80+
ProcessPoolExecutor = False
81+
else:
82+
ProcessPoolExecutor = PPE
7683
files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels,
7784
ddir=ddir)
7885
success = True
79-
if workers is not None and workers != 1 and ProcessPoolExecutor is not None:
86+
if workers is not None and workers != 1 and ProcessPoolExecutor:
8087
workers = workers or None
8188
with ProcessPoolExecutor(max_workers=workers) as executor:
8289
results = executor.map(partial(compile_file,
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
compileall: import ProcessPoolExecutor only when needed, preventing hangs on
2+
low resource platforms

0 commit comments

Comments
 (0)