Why is %PYTHONPATH% being ignored by Python using cmd on Windows?

Viewed 78

I developed a Python package on Linux, which works and my pytest succeeds. I am making it Windows compatible. I have say 'my_package' that sits in say 'C:\import_path\my_package' I set the PYTHONPATH at the command line in my virtual environment like so:

set PYTHONPATH="C:\import_path"
echo %PYTHONPATH%
"C:\import_path"

# Python script identifies this
print('PYTHONPATH = {}'.format(os.environ.get('PYTHONPATH')))
"C:\import_path"

However any Python code referencing my_package when run from a Command Prompt where this PYTHONPATH has been explicitly set, will error:

ModuleNotFoundError: No module named 'my_package'

However the code will run fine with PYTHONPATH = C:\import_path being set in the System Environment variables. It also runs fine in VSCode with:

"python.analysis.extraPaths": [
        "C:\\import_path"
    ]

Why is python.exe not reading the %PYTHONPATH% variable that was set in the cmd, but python.exe will read it when running in debug from VSCode or from the os system env variable?

1 Answers

In all probability you are running from different shell session or calling different shell sessions and the variable is not parsed to all sessions. You could try setting it like this:

setx PYTHONPATH "C:\import_path" /M

When you set a variable you should set it system-wide if you intend to use multiple sessions.

Related