0

I've gone through a lot of resources, but I simply cannot get this to work. I am trying to do an absolute import for some config files and library class files of my own, but the import fails. Here is a simple example:

└── import_test
    ├── __init__.py
    ├── config
    │   ├── __init__.py
    │   └── database.py
    └── services
        ├── __init__.py
        └── data.py

Here is the database.py

mysql = {'host':    'localhost',
         'user':    'root',
         'passwd':  'password',
         'db':      'db_name',
         'charset': 'utf8'}

and here is data.py

from import_test.config import database

When I run the data.py, I get this error.

ModuleNotFoundError: No module named 'import_test'

What am I doing wrong?

Thanks!

massimo
  • 17
  • 6
  • 2
    The Python interpreter's working directory and the setting of PYTHONPATH in the environment will make a difference here (as will, possibly, other more esoteric settings). Please update your question to include this information. Thanks! – Jean-Paul Calderone Nov 18 '18 at 22:57
  • 2
    Put it another way, print out `sys.path` before the error, and figure out if it contains the parent of `import_test`. If not, make it so. – Mad Physicist Nov 18 '18 at 22:58
  • So, this worked: import sys sys.path.insert(0, "/Users/test/import_test") But does that mean, I have to do this in every page that's burried inside subfolders? What if I have to move files and change the structure? I thought the point of absolute import was that you have more freedome to move things around... Sorry, I tried to format the code section, but I don't know how... – massimo Nov 19 '18 at 02:48
  • PYTHONPATH worked beautifully! I've created a simple shell script to add the top of the project to the PYTHONPATH and now I am calling the shell script file in the cron instead of directly calling the python file. This is the way, right? Thanks a bunch! – massimo Nov 21 '18 at 18:44

1 Answers1

0

add your top working directory to PYTHONPATH environment variable

  • So, this worked: import sys sys.path.insert(0, "/Users/test/import_test") But does that mean, I have to do this in every page that's burried inside subfolders? What if I have to move files and change the structure? I thought the point of absolute import was that you have more freedome to move things around... Sorry, I tried to format the code section, but I don't know how... – massimo Nov 19 '18 at 03:03
  • Here is good explanation about PYTHONPATH and how does it work: https://stackoverflow.com/questions/19917492/how-to-use-pythonpath Also you can create virtual environment and add needed path to PYTHONPATH permanently in activation file – p.konstantyn Nov 19 '18 at 15:19
  • It worked beautifully! I've created a simple shell script to add the top of the project to the PYTHONPATH and now I am calling the shell script file in the cron instead of directly calling the python file. This is the way, right? Thanks a bunch! – massimo Nov 21 '18 at 18:44