3
votes

My project has two dirs common and core.

root
 |----common
 |       |-----__init__.py
 |       |-----util.py
 |
 |------core
         |-----__init__.py
         |------iemoji.py

In root, I execute python core/iemoji.py, an error occurs.

Traceback (most recent call last):
File "core/iemoji.py", line 6, in module
from common import util
ImportError: No module named common

I import utils.py like this:

from common import util
3
what is common's __init__.py?Ryan Schaefer
It's empty and it's created by Pycharm (a python ide).CoXier
A module is a file, not a directory. You should be saying 'from utils' instead.dfundako
@CoXier your setup should be fine like it is, I have just tested it myself. Have you tried Alasdair's answer (print(sys.path))?FlyingTeller
Yes I print(sys.path) and I see the first item is my root /Users/myname/project/core.CoXier

3 Answers

3
votes

It looks like /path/to/root/ is not on your python path when you call python core/emoji.py. You can check by printing sys.path in your script.

import sys
print(sys.path)

You could add the root directory to your python path by setting the PYTHONPATH environment variable:

PYTHONPATH=/path/to/root python core/emoji.py

or you could set it in your script:

import sys
sys.path.append('/path/to/root')
2
votes

Set up your __init__.pys to point to the modules in their respective folders.

common's __init__.py:

from . import util

core's __init__.py:

from . import emoji

Then you should be able to call it with:

from common import util

Let me know if this works.

1
votes

add this export PYTHONPATH="$PWD" before python core/iemoji.py