How and why does PyCharm alter Python's import

2020-07-04 08:22发布

问题:

I have a PyCharm 1.2.1 on Windows. I have to edit different branches of the same project - somewhat heavy branches, because they live in different folders on disk - say it to be c:\apps\alpha and c:\apps\beta. For each such folder PYTHONPATH variable should be adjusted to point to appropriate vendor libraries which live somewhere inside project root folder (c:\alpha\vendor,...). I managed to work around this issue by starting PyCharm from cmd batch file which sets necessary PYTHONPATH variable value before starting PyCharm (so I have PyCharm.cmd inside alpha and PyCharm.cmd inside beta directories).

Problem: when I open PyCharm for editing beta folder, import statement imports modules from alpha folder! When I start python.exe interpreter from command line everything works as expected - the problem seems to be only with PyCharm.

Second strange investigation: executing print sys.path code from PyCharm and from external python.exe interpreter give different results - from PyCharm it do not show my PYTHONPATH modules. I'm a newcomer in Python and PyCharm, but this behavior looks very strange and inconsistent.

Finally I've found some settings in PyCharm IDE that looks like should allow me to resolve this issue - File -> Settings -> Python Interpreter. There I've found all paths for both alpha and beta folders. There is no way to clear this paths list, only to disable some elements. But even disabling works somewhat stupidly - I should disable/re-enable them separately for each time I edit alpha or beta "solution folders".

So final question: how one can with PyCharm edit separate projects (folders) and force PyCharm not to import modules from wrong locations?

回答1:

The correct solution is not to try to work around PyCharm's logic, but rather to use the IDE features as they're designed. That means:

  • Not use any .cmd scripts for starting up PyCharm
  • Remove all the paths specific to "alpha" and "beta" from the list of paths in Settings | Python Interpreters if any are listed there
  • Mark the "alpha/vendor" and "beta/vendor" directories as source roots in the alpha and beta projects respectively.

Then PyCharm will resolve imports correctly and generate the correct PYTHONPATH automatically when running the application from it.