Skip to content
Advertisement

ModuleNotFoundError when running script from Terminal

I have the following folder structure:

  • app
    • __init__.py
    • utils
      • __init__.py
      • transform.py
    • products
      • __init__.py
      • fish.py

In fish.py I’m importing transform as following: import utils.transform.

When I’m running fish.py from Pycharm, it works perfectly fine. However when I am running fish.py from the Terminal, I am getting error ModuleNotFoundError: No module named 'utils'.

Command I use in Terminal: from app folder python products/fish.py.

I’ve already looked into the solutions suggested here: Importing files from different folder, adding a path to the application folder into the sys.path helps. However I am wondering if there is any other way of making it work without adding two lines of code into the fish.py. It’s because I have many scripts in the /products directory, and do not want to add 2 lines of code into each of them.

I looked into some open source projects, and I saw many examples of importing modules from a parallel folder without adding anything into sys.path, e.g. here: https://github.com/jakubroztocil/httpie/blob/master/httpie/plugins/builtin.py#L5

How to make it work for my project in the same way?

Advertisement

Answer

You probably want to run python -m products.fish. The difference between that and python products/fish.py is that the former is roughly equivalent to doing import products.fish in the shell (but with __name__ set to __main__), while the latter does not have awareness of its place in a package hierarchy.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement