Home > OS >  Trouble execute project python in bash
Trouble execute project python in bash

Time:10-24

i'm trying execute project python in terminal but appear this error:

(base) hopu@docker-manager1:~/bentoml-airquality$ python src/main.py 
Traceback (most recent call last):
  File "src/main.py", line 7, in <module>
    from src import VERSION, SERVICE, DOCKER_IMAGE_NAME
ModuleNotFoundError: No module named 'src'

The project hierarchy is as follows:

Project hierarchy

If I execute project with any IDE, it works well.

CodePudding user response:

Your PYTHONPATH is determined by the directory your python executable is located, not from where you're executing it. For this reason, you should be able to import the files directly, and not from source. You're trying to import from /src, but your path is already in there. Maybe something like this might work:

from . import VERSION, SERVICE, DOCKER_IMAGE_NAME

CodePudding user response:

The interpretor is right. For from src import VERSION, SERVICE, DOCKER_IMAGE_NAME to be valid, src has to be a module or package accessible from the Python path. The problem is that the python program looks in the current directory to search for the modules or packages to run, but the current directory is not added to the Python path. So it does find the src/main.py module, but inside the interpretor it cannot find the src package.

What can be done?

  1. add the directory containing src to the Python path

    On a Unix-like system, it can be done simply with:

    PYTHONPATH=".:$PYTHONPATH" python src/main.py
    
  2. start the module as a package element:

    python -m src.main
    

That second way has an additional gift: you can then use the Pythonic from . import ....

  • Related