This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Chris Billington
Recipients Chris Billington
Date 2019-11-28.19:42:23
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1574970144.58.0.16375523531.issue38937@roundup.psfhosted.org>
In-reply-to
Content
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
History
Date User Action Args
2019-11-28 19:42:24Chris Billingtonsetrecipients: + Chris Billington
2019-11-28 19:42:24Chris Billingtonsetmessageid: <1574970144.58.0.16375523531.issue38937@roundup.psfhosted.org>
2019-11-28 19:42:24Chris Billingtonlinkissue38937 messages
2019-11-28 19:42:23Chris Billingtoncreate