Skip to content

Commit 51dc045

Browse files
authored
IPython now does not include the current working dir in sys.path, when PYTHONSAFEPATH is set or -P is used (ipython#15014)
This updates IPython so that it respects the value of the Python flag `sys.flags.safe_path`, which is usually controlled by the environment variable PYTHONSAFEPATH, and which stops Python from adding the current working directory to the `sys.path`. So now a user can do this by relying on that standard Python env var, or Python's `-P` command line flag, rather than relying on IPython's own `--ignore_cwd` command line flag.
2 parents 0a64e76 + f6fc928 commit 51dc045

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

IPython/core/shellapp.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,8 @@ def _user_ns_changed(self, change):
247247
def init_path(self):
248248
"""Add current working directory, '', to sys.path
249249
250+
Unless disabled by ignore_cwd config or sys.flags.safe_path.
251+
250252
Unlike Python's default, we insert before the first `site-packages`
251253
or `dist-packages` directory,
252254
so that it is after the standard library.
@@ -255,8 +257,10 @@ def init_path(self):
255257
Try to insert after the standard library, instead of first.
256258
.. versionchanged:: 8.0
257259
Allow optionally not including the current directory in sys.path
260+
.. versionchanged:: 9.7
261+
Respect sys.flags.safe_path (PYTHONSAFEPATH and -P flag)
258262
"""
259-
if '' in sys.path or self.ignore_cwd:
263+
if "" in sys.path or self.ignore_cwd or sys.flags.safe_path:
260264
return
261265
for idx, path in enumerate(sys.path):
262266
parent, last_part = os.path.split(path)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
Respect PYTHONSAFEPATH
2+
======================
3+
4+
IPython now respects the value of Python's flag ``sys.flags.safe_path``, a flag which is most often set by the ``PYTHONSAFEPATH`` environment variable. Setting this causes Python not to automatically include the current working directory in the sys.path.
5+
6+
IPython can already be configured to do this via the ``--ignore_cwd`` command-line flag or by setting ``c.InteractiveShellApp.ignore_cwd=True``. Now, IPython can also be configured by setting ``PYTHONSAFEPATH=1`` or by calling python with ``-P``.
7+
8+
The behavior of ``safe_path`` was described in `what's new in 3.11`_ and in `PyConfig docs`_.
9+
10+
11+
.. _what's new in 3.11: https://docs.python.org/3/whatsnew/3.11.html#whatsnew311-pythonsafepath
12+
.. _PyConfig docs: https://docs.python.org/3/c-api/init_config.html#c.PyConfig.safe_path
13+
14+

0 commit comments

Comments
 (0)