Sys.path is included in the current directory by default


I am trying a custom build of python 3.11 on linux, I see that sys.path has current directory by default, I would like to change this behavior by changing the cpython source,

>>> import sys
>>> sys.path
['', '/usr/local/lib/', '/home/mohammed/python/Python-3.11.0/Lib', '/home/mohammed/python/Python-3.11.0/build/build/lib.linux-x86_64-3.11']

where can I make desired changes in Cpython source code such that my current directory is not included by default? Also is the behavior same for windows and other systems?

There’s no need to change the CPython source; Python 3.11 added a new -P command line option and PYTHONSAFEPATH environment variable to not add the CWD to sys.path by default. Therefore, simply invoke Python via python -P or with PYTHONSAFEPATH=1 to get the behavior you’re looking for.

1 Like

I would not like to add -P every time I invoke python, is there any way to just invoke python with no cur dir in sys.path without using any options. I want to know if there is some change in configuration or change in Cpython source that I can make to get this behavior as default for my build.

As mentioned, you can set the PYTHONSAFEPATH environment variable in your shell/OS, however you normally set environment variables for your OS/shell. (E.g. .bash_profile, .zshrc, Environment Variables dialog on Windows, etc).

1 Like

Thank you Gerlach. I also tried this build on NonStop, I see some different behavior in NonStop systems, (they run on custom wrapper on top of linux OS). There sys.path doesn’t have cur directory by default. I did not find PYTHONSAFEPATH variable set there, neither did I use -P. so is this default behavior for non windows and non linux based systems?

Windows behaves the same as macOS and Linux in this regard, at least with official Python (and most other distributions I’m aware of). Given you’re using a rather non-standard proprietary OS, assuming you’re using the Python that is distributed with the system or by your system integrator or another third party, its possible that they’ve patched it to enable this by default, or otherwise it has something to do with the esoteric system architecture. You might want to ask them :slight_smile:

1 Like

Thank you Gerlach.