Skip to content

Commit d2977a3

Browse files
authored
bpo-29723: Consistently configure sys.path[0] (#575)
Directory and zipfile execution previously added the parent directory of the directory or zipfile as sys.path[0] and then subsequently overwrote it with the directory or zipfile itself. This caused problems in isolated mode, as it overwrote the "stdlib as a zip archive" entry in sys.path, as the parent directory was never added. The attempted fix to that issue in bpo-29319 created the opposite problem in *non*-isolated mode, by potentially leaving the parent directory on sys.path instead of overwriting it. This change fixes the root cause of the problem by removing the whole "add-and-overwrite" dance for sys.path[0], and instead simply never adds the parent directory to sys.path in the first place.
1 parent 6a6d090 commit d2977a3

File tree

2 files changed

+111
-28
lines changed

2 files changed

+111
-28
lines changed

Lib/test/test_cmd_line_script.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -572,6 +572,73 @@ def test_syntaxerror_indented_caret_position(self):
572572
self.assertNotIn("\f", text)
573573
self.assertIn("\n 1 + 1 = 2\n ^", text)
574574

575+
def test_consistent_sys_path_for_direct_execution(self):
576+
# This test case ensures that the following all give the same
577+
# sys.path configuration:
578+
#
579+
# ./python -s script_dir/__main__.py
580+
# ./python -s script_dir
581+
# ./python -I script_dir
582+
script = textwrap.dedent("""\
583+
import sys
584+
for entry in sys.path:
585+
print(entry)
586+
""")
587+
# Always show full path diffs on errors
588+
self.maxDiff = None
589+
with support.temp_dir() as work_dir, support.temp_dir() as script_dir:
590+
script_name = _make_test_script(script_dir, '__main__', script)
591+
# Reference output comes from directly executing __main__.py
592+
# We omit PYTHONPATH and user site to align with isolated mode
593+
p = spawn_python("-Es", script_name, cwd=work_dir)
594+
out_by_name = kill_python(p).decode().splitlines()
595+
self.assertEqual(out_by_name[0], script_dir)
596+
self.assertNotIn(work_dir, out_by_name)
597+
# Directory execution should give the same output
598+
p = spawn_python("-Es", script_dir, cwd=work_dir)
599+
out_by_dir = kill_python(p).decode().splitlines()
600+
self.assertEqual(out_by_dir, out_by_name)
601+
# As should directory execution in isolated mode
602+
p = spawn_python("-I", script_dir, cwd=work_dir)
603+
out_by_dir_isolated = kill_python(p).decode().splitlines()
604+
self.assertEqual(out_by_dir_isolated, out_by_dir, out_by_name)
605+
606+
def test_consistent_sys_path_for_module_execution(self):
607+
# This test case ensures that the following both give the same
608+
# sys.path configuration:
609+
# ./python -sm script_pkg.__main__
610+
# ./python -sm script_pkg
611+
#
612+
# And that this fails as unable to find the package:
613+
# ./python -Im script_pkg
614+
script = textwrap.dedent("""\
615+
import sys
616+
for entry in sys.path:
617+
print(entry)
618+
""")
619+
# Always show full path diffs on errors
620+
self.maxDiff = None
621+
with support.temp_dir() as work_dir:
622+
script_dir = os.path.join(work_dir, "script_pkg")
623+
os.mkdir(script_dir)
624+
script_name = _make_test_script(script_dir, '__main__', script)
625+
# Reference output comes from `-m script_pkg.__main__`
626+
# We omit PYTHONPATH and user site to better align with the
627+
# direct execution test cases
628+
p = spawn_python("-sm", "script_pkg.__main__", cwd=work_dir)
629+
out_by_module = kill_python(p).decode().splitlines()
630+
self.assertEqual(out_by_module[0], '')
631+
self.assertNotIn(script_dir, out_by_module)
632+
# Package execution should give the same output
633+
p = spawn_python("-sm", "script_pkg", cwd=work_dir)
634+
out_by_package = kill_python(p).decode().splitlines()
635+
self.assertEqual(out_by_package, out_by_module)
636+
# Isolated mode should fail with an import error
637+
exitcode, stdout, stderr = assert_python_failure(
638+
"-Im", "script_pkg", cwd=work_dir
639+
)
640+
traceback_lines = stderr.decode().splitlines()
641+
self.assertIn("No module named script_pkg", traceback_lines[-1])
575642

576643
def test_main():
577644
support.run_unittest(CmdLineTest)

Modules/main.c

Lines changed: 44 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -225,55 +225,60 @@ static int RunModule(wchar_t *modname, int set_argv0)
225225
return 0;
226226
}
227227

228-
static int
229-
RunMainFromImporter(wchar_t *filename)
228+
static PyObject *
229+
AsImportPathEntry(wchar_t *filename)
230230
{
231-
PyObject *argv0 = NULL, *importer, *sys_path, *sys_path0;
232-
int sts;
231+
PyObject *sys_path0 = NULL, *importer;
233232

234-
argv0 = PyUnicode_FromWideChar(filename, wcslen(filename));
235-
if (argv0 == NULL)
233+
sys_path0 = PyUnicode_FromWideChar(filename, wcslen(filename));
234+
if (sys_path0 == NULL)
236235
goto error;
237236

238-
importer = PyImport_GetImporter(argv0);
237+
importer = PyImport_GetImporter(sys_path0);
239238
if (importer == NULL)
240239
goto error;
241240

242241
if (importer == Py_None) {
243-
Py_DECREF(argv0);
242+
Py_DECREF(sys_path0);
244243
Py_DECREF(importer);
245-
return -1;
244+
return NULL;
246245
}
247246
Py_DECREF(importer);
247+
return sys_path0;
248+
249+
error:
250+
Py_XDECREF(sys_path0);
251+
PySys_WriteStderr("Failed checking if argv[0] is an import path entry\n");
252+
PyErr_Print();
253+
PyErr_Clear();
254+
return NULL;
255+
}
256+
257+
258+
static int
259+
RunMainFromImporter(PyObject *sys_path0)
260+
{
261+
PyObject *sys_path;
262+
int sts;
248263

249-
/* argv0 is usable as an import source, so put it in sys.path[0]
250-
and import __main__ */
264+
/* Assume sys_path0 has already been checked by AsImportPathEntry,
265+
* so put it in sys.path[0] and import __main__ */
251266
sys_path = PySys_GetObject("path");
252267
if (sys_path == NULL) {
253268
PyErr_SetString(PyExc_RuntimeError, "unable to get sys.path");
254269
goto error;
255270
}
256-
sys_path0 = PyList_GetItem(sys_path, 0);
257-
sts = 0;
258-
if (!sys_path0) {
259-
PyErr_Clear();
260-
sts = PyList_Append(sys_path, argv0);
261-
} else if (PyObject_IsTrue(sys_path0)) {
262-
sts = PyList_Insert(sys_path, 0, argv0);
263-
} else {
264-
sts = PyList_SetItem(sys_path, 0, argv0);
265-
}
271+
sts = PyList_Insert(sys_path, 0, sys_path0);
266272
if (sts) {
267-
argv0 = NULL;
273+
sys_path0 = NULL;
268274
goto error;
269275
}
270-
Py_INCREF(argv0);
271276

272277
sts = RunModule(L"__main__", 0);
273278
return sts != 0;
274279

275280
error:
276-
Py_XDECREF(argv0);
281+
Py_XDECREF(sys_path0);
277282
PyErr_Print();
278283
return 1;
279284
}
@@ -358,6 +363,7 @@ Py_Main(int argc, wchar_t **argv)
358363
int saw_unbuffered_flag = 0;
359364
char *opt;
360365
PyCompilerFlags cf;
366+
PyObject *main_importer_path = NULL;
361367
PyObject *warning_option = NULL;
362368
PyObject *warning_options = NULL;
363369

@@ -714,7 +720,17 @@ Py_Main(int argc, wchar_t **argv)
714720
argv[_PyOS_optind] = L"-m";
715721
}
716722

717-
PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
723+
if (filename != NULL) {
724+
main_importer_path = AsImportPathEntry(filename);
725+
}
726+
727+
if (main_importer_path != NULL) {
728+
/* Let RunMainFromImporter adjust sys.path[0] later */
729+
PySys_SetArgvEx(argc-_PyOS_optind, argv+_PyOS_optind, 0);
730+
} else {
731+
/* Use config settings to decide whether or not to update sys.path[0] */
732+
PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
733+
}
718734

719735
if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) &&
720736
isatty(fileno(stdin)) &&
@@ -744,11 +760,11 @@ Py_Main(int argc, wchar_t **argv)
744760

745761
sts = -1; /* keep track of whether we've already run __main__ */
746762

747-
if (filename != NULL) {
748-
sts = RunMainFromImporter(filename);
763+
if (main_importer_path != NULL) {
764+
sts = RunMainFromImporter(main_importer_path);
749765
}
750766

751-
if (sts==-1 && filename!=NULL) {
767+
if (sts==-1 && filename != NULL) {
752768
fp = _Py_wfopen(filename, L"r");
753769
if (fp == NULL) {
754770
char *cfilename_buffer;

0 commit comments

Comments
 (0)