Skip to content

Commit

Permalink
pythongh-118761: Improve import time of subprocess (pythonGH-129427)
Browse files Browse the repository at this point in the history
* subprocess: lazy import signal and locale to improve module import time
(cherry picked from commit 49f2465)

Co-authored-by: Taneli Hukkinen <3275109+hukkin@users.noreply.github.com>
  • Loading branch information
hukkin authored and miss-islington committed Jan 29, 2025
1 parent 0e54315 commit 202ee4c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
16 changes: 14 additions & 2 deletions Lib/subprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,8 @@
import builtins
import errno
import io
import locale
import os
import time
import signal
import sys
import threading
import warnings
Expand Down Expand Up @@ -138,6 +136,8 @@ def __init__(self, returncode, cmd, output=None, stderr=None):

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))
Expand Down Expand Up @@ -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()


Expand Down Expand Up @@ -1655,6 +1657,9 @@ def send_signal(self, sig):
# 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:
Expand Down Expand Up @@ -1759,6 +1764,9 @@ def _posix_spawn(self, args, executable, env, restore_signals,

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'):
Expand Down Expand Up @@ -2208,9 +2216,13 @@ def send_signal(self, sig):
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)
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Improve import time of :mod:`subprocess` by lazy importing ``locale`` and
``signal``. Patch by Taneli Hukkinen.

0 comments on commit 202ee4c

Please sign in to comment.