Serob_b
Serob_b

Reputation: 1069

Can not import package created in pycharm

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

enter image description here

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

I get an error:

ModuleNotFoundError: No module named 'bgr'

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

Upvotes: 1

Views: 626

Answers (2)

Djib2011
Djib2011

Reputation: 7442

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.

Just go to the test_me directory and type:

python asd/one.py

It should work

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


Edit:

You could also use relative imports.

from ..bgr import two

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

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

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.

Upvotes: 1

Toan Quoc Ho
Toan Quoc Ho

Reputation: 3378

Follow your comments above, I've see that you want to work on asd folder. Don't want your bgr to be visible everywhere. So I bet that PYTHONPATH is not an option that you looking for. Here is something you can try:

import sys
sys.path.insert(0, "../")
from bgr import two

This will add bgr module and allow you to use it like your current expectation. More details here: https://askubuntu.com/questions/470982/how-to-add-a-python-module-to-syspath

Upvotes: 1

Related Questions