pythonunit-testingpackage

ImportError: No module named 'app'


I am working on a project with following tree structure:

Project
  app
    main.py
    svg_to_png.py
    __init__.py
    tests
       __init__.py
       unittests
          basic_test.py
          __init__.py

I am importing app functions to basic_tests by using

from app.main import *

when I execute the basic_test.py, it gives the following error:

ImportError: No module named 'app'

Also, while in the top directory of the project, when I type python3 -m app.main, the program executes for a while, then gives the same import error at the following line

from app.svg_to_png import do_svg2png


Solution

  • You can't import from higher up the directory structure that way. One way to do it would be

    import sys
    sys.path.append("../..")
    from main import *
    

    For the second import, you'd want to do

    from .svg_to_png import do_svg2png
    

    See this section of the Python documentation specifically