LJHW
LJHW

Reputation: 445

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

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?

Upvotes: 3

Views: 238

Answers (1)

Eduard Luca
Eduard Luca

Reputation: 26

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.

Upvotes: 1

Related Questions