Chris Billington <chrisjbilling...@gmail.com> added the comment:
I see. site.py calls exec() from within a function, and therefore the code is executed in the context of that function's locals and the site module globals. This means the code in .pth files can access (but not add new) local names from the site.addpackage() function: $ echo 'import sys; f.close()' | sudo tee /usr/lib/python3.8/site-packages/test.pth import sys; f.close() $ python Fatal Python error: init_import_size: Failed to import the site module Python runtime state: initialized Traceback (most recent call last): File "/usr/lib/python3.8/site.py", line 580, in <module> main() File "/usr/lib/python3.8/site.py", line 567, in main known_paths = addsitepackages(known_paths) File "/usr/lib/python3.8/site.py", line 350, in addsitepackages addsitedir(sitedir, known_paths) File "/usr/lib/python3.8/site.py", line 208, in addsitedir addpackage(sitedir, name, known_paths) File "/usr/lib/python3.8/site.py", line 164, in addpackage for n, line in enumerate(f): ValueError: I/O operation on closed file. The example with the sys module worked because sys is in the globals the site module already. Probably site.addpackage() should exec() code it its own environment: if line.startswith(("import ", "import\t")): exec(line, {}) continue (added empty dict for exec() call) or for backward compatibility for .pth files that are using globals from the site module without importing them (such as sys or os): if line.startswith(("import ", "import\t")): exec(line, globals().copy()) continue This resolves the original issue ---------- _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue38937> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com