Skip to content

Commit 632567d

Browse files
authored
Support PYTHONSAFEPATH
1 parent 3f0a4c1 commit 632567d

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

coverage/execfile.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,10 @@ def prepare(self) -> None:
9090
This needs to happen before any importing, and without importing anything.
9191
"""
9292
path0: Optional[str]
93-
if self.as_module:
93+
if os.environ.get('PYTHONSAFEPATH', ''):
94+
# See https://docs.python.org/3/using/cmdline.html#cmdoption-P
95+
path0 = None
96+
elif self.as_module:
9497
path0 = os.getcwd()
9598
elif os.path.isdir(self.arg0):
9699
# Running a directory means running the __main__.py file in that

tests/test_execfile.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import py_compile
1414
import re
1515
import sys
16-
16+
from unittest import mock
1717
from typing import Any, Iterator
1818

1919
import pytest
@@ -306,6 +306,14 @@ def test_pkg1_init(self) -> None:
306306
assert out == "pkg1.__init__: pkg1\npkg1.__init__: __main__\n"
307307
assert err == ""
308308

309+
def test_pythonpath(self) -> None:
310+
with mock.patch.dict(os.environ, {"PYTHONSAFEPATH": "1"}):
311+
run_python_module([TRY_EXECFILE])
312+
out, err = self.stdouterr()
313+
mod_globs = json.loads(out)
314+
assert os.cwd() not in mod_globs["path"]
315+
assert err == ""
316+
309317
def test_no_such_module(self) -> None:
310318
with pytest.raises(NoSource, match="No module named '?i_dont_exist'?"):
311319
run_python_module(["i_dont_exist"])

0 commit comments

Comments
 (0)