Python flag/envvar not to put current directory to sys.path (but don't ignore PYTHONPATH)

Hello. There are currently two similar ways to invoke pytest: either via the pytest executable or python -m pytest. It has a documented difference: calling via python will also add the current directory to sys.path.

As I understand things, calling tools that are specifically tied to a Python version/installation/venv via python -m is The Right Thing To Do™. In a multi-Python environment with system installed pytest (etc.), the distributors don’t need to worry about creating /usr/bin/pytest-3.8, /usr/bin/pytest-3.9 etc. when the users can run python3.8 -m pytest. IIRC the pyvenv command was deprecated and removed for the same reasons. (This does not apply for tools where the Python version is implementation detail, such as pygmentize.)

In Fedora, we’d like to advise packagers to invoke pytest via python -m pytest. However, we don’t like the current working directory added to sys.path. We set our own $PYTHONPATH to <path_to_the_buildroot>/usr/lib(64)?)/pythonX.Y/site-packages so we actually test the content we will ship.

Would it be possible to have a Python flag that prevents adding the current working directory to sys.path? The -I flag does that, but at the same time, all PYTHON* environment variables are ignored, too. That prevent us from doing the two following things simultaneously:

  • set and use custom $PYTHONPATH
  • ignore the current working directory

In the language of precmdline_parse_cmdline I’d like to be able to have cmdline->isolated = 1 and cmdline->use_environment = 1.

3 Likes

Another option is to no longer add the current directory to sys.path by default. It was discussed a few times.

2 Likes

Also see https://bugs.python.org/issue13475 (“Add ‘–mainpath’/’–nomainpath’ command line options to override sys.path[0] initialisation”).

2 Likes