There is a project:

project |__library | |__python | |__resource | |__ __init__.py |__web |__gui |__main.py 

the project is launched through the launch of the file web / gui / main.py, but when you run this launch an error occurs

 Traceback (most recent call last): File "web/gui/main.py", line 8, in <module> import library.python.resource as resource ImportError: No module named python.resource 

I run from the project folder:

 python web/gui/main.py 

How to run the project correctly so that he sees this module?

    2 answers 2

    In each folder that you want to transform into a Python package, add __init__.py files.

    You can also main.py in __main__.py , then you can run the script as:

     project/$ python -m web.gui 

    Since the project/ in pythonpath in this case, the import library.python.resource is an absolute import (the library is a top-level package). In modules running as scripts ( __name__ == '__main__' ), there are restrictions on relative imports. -m form allows explicit relative imports ( PEP 366 ).

      When you run the script directly, it automatically considers the directory where this script is located as the root. Thus, everything that is above it will not be available unless you add the desired path to import into sys.path (which is not very good).

      Therefore, you have 2 choices:

      1. Create an initial script in the root directory of the project, initially launch it, and only then import other modules
      2. Run main.py as a module, using the - m parameter (and this is the most correct approach). Thus, the root directory is saved, and you can safely import any module in the project. This is done as follows:

      python -m web.gui.main

      In addition, for python 2.x, you must declare each folder that somehow participates in the import as a package (that is, add __init__.py to it). In your case, you need to do this with folders: library , python , web and gui . At the same time, for Python 3.x, this need already disappears. Thanks @jfs for the addition.

      I advise you to read:

      • without adding __init__.py it will not work. - jfs
      • @jfs will try again later, but it seems to work for me (if __init__.py is at least in the final folders, i.e. in gui and resource in this case). At least in 3-ke. Unsubscribe as I check. - Hast
      • we are discussing Python 2. In each folder that you consider as the Python package, you should add __init__.py , and not just in the most nested one. - jfs
      • @jfs Yes, sorry, did not pay attention to the version. The answer is updated. - Hast
      • one
        In Python 3, if you do not add __init__.py , then namespace packages are created - this will work, but semantically it’s not correct to use namespace packages here (they are for another: when you have a package in several folders can be scattered). Like on Python 2 and 3, if you want to consider the folder as a Python package, add __init__.py . - jfs