本文介绍了无法导入在pycharm中创建的包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在pycharm(Windows)中创建了2个python包(init.py-s为空),

I have created 2 python packages in pycharm (Windows) (init.py-s are empty),

并将文件从第二个程序包导入到第一个程序包( one.p y):

and imported a file from the second package to the first one (one.py):

from bgr import two

仅此而已,没有循环进口.当我从命令行运行文件时:

That's all, nothing else, no circular imports.When I run the file form the command line:

python one.py

我收到一个错误:

ModuleNotFoundError: No module named 'bgr'

有趣的是,当我从pycharm UI运行时,它可以正常工作.是什么原因导致这种奇怪的行为.

What's interesting, it works normally when I run from the pycharm UI. What can cause such a strange behavior.

推荐答案

如果您的工作目录位于 asd 内,则期望内部有一个名为 bgr 的模块 asd .在pycharm中,您的工作目录是 test_me ,它位于 asd 之外,这就是它起作用的原因.

If your working directory is inside asd, then it expects a module called bgr inside asd. In pycharm your working directory is test_me which is outside asd and that's why it works.

只需转到 test_me 目录并键入:

python asd/one.py

它应该工作

另一种选择是将 bgr 添加到 PYTHONPATH 环境变量中.然后可以从任何地方导入 bgr .

Another option is to add bgr to the PYTHONPATH environmental variable. Then bgr can be imported from anywhere.

您还可以使用相对导入.

from ..bgr import two

但是,为了运行此操作,需要,您必须位于 asd 之内(在 test_me 中不起作用).从运行脚本的位置而不是从导入脚本的位置搜索模块.

This however in order to run requires that you are inside asd (it won't work from test_me). The modules are searched from where you are running the script not from where the script importing them is.

有一种变通办法可以使其在两个地点都可以使用:

There is a workaround to make it work for both locations:

try:
    from bgr import two
except ModuleNotFoundError:
    from ..bgr import two

这仅适用于这两个位置(在 test_me 内部和 test_me/asd 内部).在其他任何地方都无法使用.

This only works for these two locations though (inside test_me and inside test_me/asd). It won't work for any other locations.

有两种变通办法可以使其在任何位置上正常工作,例如在条纹内更改cwd(例如,使用 os.chdir())或通过在脚本中更改 PYTHONPATH 时(例如 sys.path.append()),但不推荐,因为它们只能工作仅在您不更改计算机位置的情况下使用.

There are a couple of workarounds to make it work for any location such as changing your cwd while inside the stript (e.g. with os.chdir()) or by changing the PYTHONPATH while inside the script (e.g. sys.path.append()), but they aren't recommended because they will only work for your computer and only if you don't change their location.

这篇关于无法导入在pycharm中创建的包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:16