From f65aa0d1bf7b636ab8f9d226429205854b24cd7a Mon Sep 17 00:00:00 2001 From: "Miss Islington (bot)" <31488909+miss-islington@users.noreply.github.com> Date: Wed, 29 Jan 2025 17:48:48 +0100 Subject: [PATCH] [3.12] gh-118761: Improve import time of `subprocess` (GH-129427) (#129448) gh-118761: Improve import time of `subprocess` (GH-129427) * subprocess: lazy import signal and locale to improve module import time (cherry picked from commit 49f24650e4541456872490ec2b59d6d186204891) Co-authored-by: Taneli Hukkinen <3275109+hukkin@users.noreply.github.com> --- Lib/subprocess.py | 16 ++++++++++++++-- ...025-01-29-10-53-32.gh-issue-118761.i8wjpV.rst | 2 ++ 2 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2025-01-29-10-53-32.gh-issue-118761.i8wjpV.rst diff --git a/Lib/subprocess.py b/Lib/subprocess.py index 881a9ce800ae..3ec39ca3e61e 100644 --- a/Lib/subprocess.py +++ b/Lib/subprocess.py @@ -43,10 +43,8 @@ getstatusoutput(...): Runs a command in the shell, waits for it to complete, import builtins import errno import io -import locale import os import time -import signal import sys import threading import warnings @@ -138,6 +136,8 @@ class CalledProcessError(SubprocessError): def __str__(self): if self.returncode and self.returncode < 0: + # Lazy import to improve module import time + import signal try: return "Command '%s' died with %r." % ( self.cmd, signal.Signals(-self.returncode)) @@ -375,6 +375,8 @@ def _text_encoding(): if sys.flags.utf8_mode: return "utf-8" else: + # Lazy import to improve module import time + import locale return locale.getencoding() @@ -1655,6 +1657,9 @@ class Popen: # Don't signal a process that we know has already died. if self.returncode is not None: return + + # Lazy import to improve module import time + import signal if sig == signal.SIGTERM: self.terminate() elif sig == signal.CTRL_C_EVENT: @@ -1759,6 +1764,9 @@ class Popen: kwargs = {} if restore_signals: + # Lazy import to improve module import time + import signal + # See _Py_RestoreSignals() in Python/pylifecycle.c sigset = [] for signame in ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ'): @@ -2208,9 +2216,13 @@ class Popen: def terminate(self): """Terminate the process with SIGTERM """ + # Lazy import to improve module import time + import signal self.send_signal(signal.SIGTERM) def kill(self): """Kill the process with SIGKILL """ + # Lazy import to improve module import time + import signal self.send_signal(signal.SIGKILL) diff --git a/Misc/NEWS.d/next/Library/2025-01-29-10-53-32.gh-issue-118761.i8wjpV.rst b/Misc/NEWS.d/next/Library/2025-01-29-10-53-32.gh-issue-118761.i8wjpV.rst new file mode 100644 index 000000000000..0762cbe5d639 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-01-29-10-53-32.gh-issue-118761.i8wjpV.rst @@ -0,0 +1,2 @@ +Improve import time of :mod:`subprocess` by lazy importing ``locale`` and +``signal``. Patch by Taneli Hukkinen. -- 2.47.3