Reputation: 2198
i'm going to feel like an absolute idiot for this, and i don't know if it's because it's late Friday, but i'm having a hard time understanding why i'm having an issue with this incredibly simple code.
Directory structure:
~/testapp/
~/testapp/__init__.py
~/testapp/settings.py
~/testapp/workers/a.py
~/testapp/settings.py:
x = 1
~/testapp/workers/a.py:
from settings import x
when running ~/testapp/workers/a.py through PyCharm, it runs fine. however when running in a terminal, i get:
m@G750JW:~$ python testapp/workers/a.py
Traceback (most recent call last):
File "testapp/workers/a.py", line 1, in <module>
from settings import x
ImportError: No module named settings
i have also tried the following in ~/testapp/workers/a.py:
from testapp.settings import x
and got the same error. i've also tried:
from ..settings import x
but this will return:
m@G750JW:~/$ python testapp/workers/a.py
Traceback (most recent call last):
File "python testapp/workers/a.py", line 1, in <module>
from ..settings import testvar
ValueError: Attempted relative import in non-package
i've ran a lot of apps previously that used this same import method, and have never had a problem. i'm not sure why all of a sudden this is happening.
when looking at other issues like this on stackoverflow and google, everyone mentions setting and checking system paths, which i have done. as mentioned, running this through PyCharm works fine. if i change ~/testapp/workers/a.py to print sys.path, sys.executable, and os.getcwd() before the import, the results in PyCharm and the console are the same.
Upvotes: 0
Views: 2959
Reputation: 350
The issue is related, as you say, to paths... When you execute your code, the interpreter has a list of places to look for the things you are importing. In this case, it doesn't know about your project's root directory.
To solve the problem, set the environment variable PYTHONPATH to your project's root directory. Something like this:
export PYTHONPATH=~/testapp
Upvotes: 1