PyCharm Virtualenv Insanity

Ok, I nearly went crazy trying to figure out why my virtualenv wasn't working, so I thought I'd share if anyone is encountering a similar issue. I actually gave up using PyCharm a while ago, because I wrongly thought it just sucked at virtualenvs on Windows, but I simply had an unintended environment variable set in Windows. That environment variable is PYTHONHOME.

I only had one interpreter set-up for my project: that of my virtualenv, but PyCharm kept complaining about packages missing, ones that were clearly in my virtualenv, and that I could import if I activated my virtualenv with activate.bat and ran python.exe. I descended into madness: scouring the internet, uninstalling all JetBrains products and associated cached files from my computer, wiping out all metadata files in my projects, even uninstalling and reinstalling Python.

I just couldn't understand why when I ran python inside PyCharm, my sys.executable was correctly set to my virtualenv's python.exe, but my site.getsitepackages() returned only the default python library paths, not the paths in my virtualenv. However, after hours chasing my tail, I decided to run the virtualenv's python.exe in cmd.exe without activating the virtualenv. Here I found the same issue of the executable path being correct but not site-packages. Then, I decided to look at the source of activate.bat, and I noticed it sets PYTHONHOME= as part of the activation process.

So I deleted PYTHONHOME, and all was well in PyCharm!!!! I don't know when/why I ever set this, likely when I was first learning Python and superstitiously set it to fix another issue. PYTHONHOME AND VIRTUALENVS CANNOT COEXIST if you don't activate the virtualenv. Why? Because PYTHONHOME hard-sets where to look for python packages, when typically python will look relative to the python executable. My PYTHONHOME was set to C:\Python27, so my virtualenv's python.exe just always looked there.

See this:

JetBrains, could you put some sort of notification when someone is trying to use a virtualenv but has PYTHONHOME set? I would love if random future users wouldn't have to waste so much time on this issue. I think the product is really the best Python IDE, but I went down other roads simply because I couldn't get virtualenv to work. At least I learned VIM along the way and PyCharm has a pretty good plug-in now that I am coming back :)

P.S.: What actually confused me the most is that starting python.exe from Git bash without activating the virtualenv never suffered from the same issue as in cmd.exe.

1 comment
Comment actions Permalink

I think that's a good idea, and you're right that ideas like this are great ways to avoid massive Python frustration. Can you file a feature request in the PyCharm issue tracker to get it on the radar?


Please sign in to leave a comment.