PyCharm 如何以及为何改变 Python 的导入逻辑?
我在 Windows 上有一个 PyCharm 1.2.1。我必须编辑同一项目的不同分支 - 有点重的分支,因为它们位于磁盘上的不同文件夹中 - 假设它是 c:\apps\alpha
和 c:\apps\测试版
。对于每个此类文件夹,应调整 PYTHONPATH 变量以指向位于项目根文件夹内某处的适当供应商库(c:\alpha\vendor
,...)。我设法通过从 cmd 批处理文件启动 PyCharm 来解决这个问题,该文件在启动 PyCharm 之前设置必要的 PYTHONPATH 变量值(所以我在 alpha
和 中有
)。PyCharm.cmd
beta
目录中的 PyCharm.cmd
问题:当我打开 PyCharm 编辑 beta
文件夹时,import
语句从 alpha
文件夹导入模块!当我从命令行启动 python.exe
解释器时,一切都按预期工作 - 问题似乎仅适用于 PyCharm。
第二个奇怪的调查:从 PyCharm 和外部 python.exe 解释器执行 print sys.path
代码给出了不同的结果 - 从 PyCharm 中它不显示我的 PYTHONPATH 模块。我是 Python 和 PyCharm 的新手,但这种行为看起来非常奇怪且不一致。
最后,我在 PyCharm IDE 中找到了一些设置,看起来应该可以让我解决这个问题 - File ->设置-> Python 解释器
。在那里我找到了 alpha
和 beta
文件夹的所有路径。无法清除此路径列表,只能禁用某些元素。但即使禁用也有点愚蠢 - 我应该在每次编辑 alpha
或 beta
“解决方案文件夹”时单独禁用/重新启用它们。
最后一个问题:如何使用 PyCharm 编辑单独的项目(文件夹)并强制 PyCharm 不从错误位置导入模块?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正确的解决方案不是尝试绕过 PyCharm 的逻辑,而是使用设计好的 IDE 功能。这意味着:
然后 PyCharm 将正确解析导入并在运行应用程序时自动生成正确的 PYTHONPATH。
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:
Then PyCharm will resolve imports correctly and generate the correct PYTHONPATH automatically when running the application from it.