Skip to content

Commit f502c8f

Browse files
[3.13] gh-118761: Improve import time of subprocess (GH-129427) (#129447)
gh-118761: Improve import time of `subprocess` (GH-129427) * subprocess: lazy import signal and locale to improve module import time (cherry picked from commit 49f2465) Co-authored-by: Taneli Hukkinen <[email protected]>
1 parent 1883667 commit f502c8f

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

Lib/subprocess.py

+14-2
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,8 @@
4343
import builtins
4444
import errno
4545
import io
46-
import locale
4746
import os
4847
import time
49-
import signal
5048
import sys
5149
import threading
5250
import warnings
@@ -144,6 +142,8 @@ def __init__(self, returncode, cmd, output=None, stderr=None):
144142

145143
def __str__(self):
146144
if self.returncode and self.returncode < 0:
145+
# Lazy import to improve module import time
146+
import signal
147147
try:
148148
return "Command '%s' died with %r." % (
149149
self.cmd, signal.Signals(-self.returncode))
@@ -381,6 +381,8 @@ def _text_encoding():
381381
if sys.flags.utf8_mode:
382382
return "utf-8"
383383
else:
384+
# Lazy import to improve module import time
385+
import locale
384386
return locale.getencoding()
385387

386388

@@ -1665,6 +1667,9 @@ def send_signal(self, sig):
16651667
# Don't signal a process that we know has already died.
16661668
if self.returncode is not None:
16671669
return
1670+
1671+
# Lazy import to improve module import time
1672+
import signal
16681673
if sig == signal.SIGTERM:
16691674
self.terminate()
16701675
elif sig == signal.CTRL_C_EVENT:
@@ -1766,6 +1771,9 @@ def _posix_spawn(self, args, executable, env, restore_signals, close_fds,
17661771
"""Execute program using os.posix_spawn()."""
17671772
kwargs = {}
17681773
if restore_signals:
1774+
# Lazy import to improve module import time
1775+
import signal
1776+
17691777
# See _Py_RestoreSignals() in Python/pylifecycle.c
17701778
sigset = []
17711779
for signame in ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ'):
@@ -2215,9 +2223,13 @@ def send_signal(self, sig):
22152223
def terminate(self):
22162224
"""Terminate the process with SIGTERM
22172225
"""
2226+
# Lazy import to improve module import time
2227+
import signal
22182228
self.send_signal(signal.SIGTERM)
22192229

22202230
def kill(self):
22212231
"""Kill the process with SIGKILL
22222232
"""
2233+
# Lazy import to improve module import time
2234+
import signal
22232235
self.send_signal(signal.SIGKILL)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve import time of :mod:`subprocess` by lazy importing ``locale`` and
2+
``signal``. Patch by Taneli Hukkinen.

0 commit comments

Comments
 (0)