Environment $PATH different when using venv

2019-01-26 19:43发布

问题:

I'm using PyCharm on a mac (OSX mavericks) to run a simple script shown below. All it does is print the PATH variable. I have a virtualenv in the project directory. I added a Run Configuration in PyCharm and tried it with different Pythons:

# file mytest.py
import os
print "PATH: ", os.environ['PATH']

When I run with the system default python (/usr/bin/python) it prints the correct value for PATH (i.e. the PATH as I have configured in my .bash_profile file,) which is kind of long and contains many directories.

But when I choose the venv's Python, the path is reduced to only: /usr/bin:/bin:/usr/sbin:/sbin:/Users/myname/projects/myproj/venv/bin

This doesn't happen if I run the script from a terminal window. In this case it shows the correct PATH for both the system's python and the venv python. It also doesn't happen if I deactivate the venv and run venv/bin/python mytest.py.

Anyone knows how to make the correct PATH value be set when running from PyCharm and using venv?

回答1:

you should probably know that all environment variables are inherited. When you define environment variable in your .bash_profile it becomes available in your terminal (bash), and in all processes that will be started from terminal (These processes will be children for the bash process). That's why you are getting expected values when running your script from within the terminal.

You start PyCharm not from a terminal, so it doesn't inherit PATH. And so do Python or venv (they launched from PyCharm).

To solve your issue you have 3 options here: just start PyCharm from terminal or move PATH variable definition from .bash_profile to session init scripts (PATH will be defined system-wide) or Duplicate your PATH in PyCharm's run configuration (it has such option over there)

Good luck!



回答2:

I built something for SublimeLint that figures out your shell's PATH in Python.

https://github.com/lunixbochs/sublimelint/blob/st3/lint/util.py#L57

Basically, it runs $SHELL --login, echoes your path, and parses it.

The gist is:

import os
import subprocess

shell = os.path.basename(os.environ['SHELL'])
output = subprocess.Popen(
    (shell, '--login', '-c', 'echo __SEP__$PATH'),
    stdout=subprocess.PIPE).communicate()[0] or ''
print output.split('__SEP__', 1)[1].split(':')


回答3:

The problem for me on windows was case related: it's the difference between Path and PATH.

If you choose:

  • Edit configurations
    • Environment Variables
      • Show (down in the bottom right corner)

This shows the environment variables. On my system there is no PATH, only Path.

Defining a new PATH environment variable wouldn't work, but Path worked fine.



回答4:

There's a workaround in my case.

To modify the environment variable PATH, I usually just need to add extra paths to the PYTHONPATH variable in the run configuration's environment variables setting. PYTHONPATH will then be added to PATH.