Skip to content

Commit 038cace

Browse files
committed
gh-148014: Accept a function name in -X presite option
1 parent 9b08f8c commit 038cace

File tree

9 files changed

+95
-36
lines changed

9 files changed

+95
-36
lines changed

Doc/c-api/init_config.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1807,10 +1807,10 @@ PyConfig
18071807
18081808
.. c:member:: wchar_t* run_presite
18091809
1810-
``package.module`` path to module that should be imported before
1811-
``site.py`` is run.
1810+
``module`` or ``module:func`` entry point that should be executed before
1811+
the :mod:`site` module is imported.
18121812
1813-
Set by the :option:`-X presite=package.module <-X>` command-line
1813+
Set by the :option:`-X presite=module:func <-X>` command-line
18141814
option and the :envvar:`PYTHON_PRESITE` environment variable.
18151815
The command-line option takes precedence.
18161816

Doc/using/cmdline.rst

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -654,13 +654,17 @@ Miscellaneous options
654654

655655
.. versionadded:: 3.13
656656

657-
* :samp:`-X presite={package.module}` specifies a module that should be
658-
imported before the :mod:`site` module is executed and before the
657+
* :samp:`-X presite={module}` or :samp:`-X presite={module:func}` specifies
658+
an entry point that should be executed before the :mod:`site` module is
659+
executed and before the
659660
:mod:`__main__` module exists. Therefore, the imported module isn't
660661
:mod:`__main__`. This can be used to execute code early during Python
661662
initialization. Python needs to be :ref:`built in debug mode <debug-build>`
662663
for this option to exist. See also :envvar:`PYTHON_PRESITE`.
663664

665+
.. versionchange:: next
666+
Accept also ``module:func`` entry point format.
667+
664668
.. versionadded:: 3.13
665669

666670
* :samp:`-X gil={0,1}` forces the GIL to be disabled or enabled,
@@ -1451,4 +1455,7 @@ Debug-mode variables
14511455

14521456
Needs Python configured with the :option:`--with-pydebug` build option.
14531457

1458+
.. versionchange:: next
1459+
Accept also ``module:func`` entry point format.
1460+
14541461
.. versionadded:: 3.13

Lib/test/_test_embed_structseq.py

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -47,16 +47,21 @@ def test_sys_funcs(self):
4747
self.check_structseq(type(obj))
4848

4949

50-
try:
51-
unittest.main(
52-
module=(
53-
'__main__'
54-
if __name__ == '__main__'
55-
# Avoiding a circular import:
56-
else sys.modules['test._test_embed_structseq']
50+
def main():
51+
try:
52+
unittest.main(
53+
module=(
54+
'__main__'
55+
if __name__ == '__main__'
56+
# Avoiding a circular import:
57+
else sys.modules['test._test_embed_structseq']
58+
)
5759
)
58-
)
59-
except SystemExit as exc:
60-
if exc.args[0] != 0:
61-
raise
62-
print("Tests passed")
60+
except SystemExit as exc:
61+
if exc.args[0] != 0:
62+
raise
63+
print("Tests passed")
64+
65+
66+
if __name__ == "__main__":
67+
main()

Lib/test/cov.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
"""A minimal hook for gathering line coverage of the standard library.
22
3-
Designed to be used with -Xpresite= which means:
4-
* it installs itself on import
5-
* it's not imported as `__main__` so can't use the ifmain idiom
3+
Designed to be used with -Xpresite=test.cov:enable which means:
4+
65
* it can't import anything besides `sys` to avoid tainting gathered coverage
76
* filenames are not normalized
87
@@ -45,4 +44,5 @@ def disable():
4544
mon.free_tool_id(mon.COVERAGE_ID)
4645

4746

48-
enable()
47+
if __name__ == "__main__":
48+
enable()

Lib/test/libregrtest/runtests.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ def create_python_cmd(self) -> list[str]:
159159
if '-u' not in python_opts:
160160
cmd.append('-u') # Unbuffered stdout and stderr
161161
if self.coverage:
162-
cmd.append("-Xpresite=test.cov")
162+
cmd.append("-Xpresite=test.cov:enable")
163163
return cmd
164164

165165
def bisect_cmd_args(self) -> list[str]:

Lib/test/support/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1396,7 +1396,7 @@ def trace_wrapper(*args, **kwargs):
13961396
sys.settrace(original_trace)
13971397

13981398
coverage_wrapper = trace_wrapper
1399-
if 'test.cov' in sys.modules: # -Xpresite=test.cov used
1399+
if 'test.cov' in sys.modules: # -Xpresite=test.cov:enable used
14001400
cov = sys.monitoring.COVERAGE_ID
14011401
@functools.wraps(func)
14021402
def coverage_wrapper(*args, **kwargs):

Lib/test/test_embed.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2051,7 +2051,7 @@ def test_no_memleak(self):
20512051
def test_presite(self):
20522052
cmd = [
20532053
sys.executable,
2054-
"-I", "-X", "presite=test._test_embed_structseq",
2054+
"-I", "-X", "presite=test._test_embed_structseq:main",
20552055
"-c", "print('unique-python-message')",
20562056
]
20572057
proc = subprocess.run(
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Accept a function name in :option:`-X presite <-X>` command line option and
2+
:envvar:`PYTHON_PRESITE` environment variable. Patch by Victor Stinner.

Python/pylifecycle.c

Lines changed: 57 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1228,22 +1228,67 @@ run_presite(PyThreadState *tstate)
12281228
return;
12291229
}
12301230

1231-
PyObject *presite_modname = PyUnicode_FromWideChar(
1232-
config->run_presite,
1233-
wcslen(config->run_presite)
1234-
);
1235-
if (presite_modname == NULL) {
1236-
fprintf(stderr, "Could not convert pre-site module name to unicode\n");
1231+
PyObject *presite = PyUnicode_FromWideChar(config->run_presite, -1);
1232+
if (presite == NULL) {
1233+
fprintf(stderr, "Could not convert pre-site command to Unicode\n");
1234+
_PyErr_Print(tstate);
1235+
return;
1236+
}
1237+
1238+
// Accept "mod_name" and "mod_name:func_name" entry point syntax
1239+
Py_ssize_t len = PyUnicode_GET_LENGTH(presite);
1240+
Py_ssize_t pos = PyUnicode_FindChar(presite, ':', 0, len, 1);
1241+
PyObject *mod_name = NULL;
1242+
PyObject *func_name = NULL;
1243+
PyObject *module = NULL;
1244+
if (pos > 0) {
1245+
mod_name = PyUnicode_Substring(presite, 0, pos);
1246+
if (mod_name == NULL) {
1247+
goto error;
1248+
}
1249+
1250+
func_name = PyUnicode_Substring(presite, pos + 1, len);
1251+
if (func_name == NULL) {
1252+
goto error;
1253+
}
12371254
}
12381255
else {
1239-
PyObject *presite = PyImport_Import(presite_modname);
1240-
if (presite == NULL) {
1241-
fprintf(stderr, "pre-site import failed:\n");
1242-
_PyErr_Print(tstate);
1256+
mod_name = Py_NewRef(presite);
1257+
}
1258+
1259+
module = PyImport_Import(mod_name);
1260+
if (module == NULL) {
1261+
goto error;
1262+
}
1263+
1264+
if (func_name != NULL) {
1265+
PyObject *func = PyObject_GetAttr(module, func_name);
1266+
if (func == NULL) {
1267+
goto error;
1268+
}
1269+
1270+
PyObject *res = PyObject_CallNoArgs(func);
1271+
Py_DECREF(func);
1272+
if (res == NULL) {
1273+
goto error;
12431274
}
1244-
Py_XDECREF(presite);
1245-
Py_DECREF(presite_modname);
1275+
Py_DECREF(res);
12461276
}
1277+
1278+
Py_DECREF(presite);
1279+
Py_DECREF(mod_name);
1280+
Py_XDECREF(func_name);
1281+
Py_DECREF(module);
1282+
return;
1283+
1284+
error:
1285+
fprintf(stderr, "pre-site failed:\n");
1286+
_PyErr_Print(tstate);
1287+
1288+
Py_DECREF(presite);
1289+
Py_XDECREF(mod_name);
1290+
Py_XDECREF(func_name);
1291+
Py_XDECREF(module);
12471292
}
12481293
#endif
12491294

0 commit comments

Comments
 (0)