Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python absolute import not working on Ubuntu server

My project has the following structure:

server/ (root of project)
  |
  |--- __init__.py
  |--- requirements.txt
  |--- env/ (virtual environment)
  |--- app/ (main app folder)
        |--- __init__.py (defines a 'app = Flask(__name__)' object)
        |--- app.py (runs app on local server)
        |--- models.py
        |--- views.py

The way I import different modules in app.py on my local machine is do:

# /server/app/app.py

from server.app import app 
from server.app.models import *
from server.app.views import *

It works fine on my local machine (using PyCharm IDE, and the Python binary inside virtual environment folder /server/env/bin/.

However, when I push this to the production server running Ubuntu, where I install all dependencies globally, it keeps throwing the error no module named server.app when I run:

python server/app/app.py

Does anyone know why?

like image 465
benjaminz Avatar asked Mar 09 '26 03:03

benjaminz


1 Answers

Any IDE environment usually sets the pythonpath. E.g. in eclipse right click your project and see the properties. You will see that your main project is listed in the pythonpath. This path is used to locate modules.

Now in your production code you are not in your IDE. So normal python interpreter cannot find your path. Hence you need to specify this.

One way is to add sys.path.append('/path/to/the/project') before you do your import (This should be done for the first script that got executed, in this case app.py, that way you only need to do this once).

You can also add your path permanently to your production environment. See this post.

like image 123
Rash Avatar answered Mar 10 '26 16:03

Rash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!