Python unable to import custom module despite having __init__.py

Python unable to import custom module despite having __init__.py

Run from the parent folder for foldername:

    $ python -m foldername.main

If you rename main.py to __main__.py then you could run it as (since Python 2.7):

    $ python -m foldername

python -m adds implicitly current directory to your python path (sys.path).

Parent Folder/
└── foldername
    ├── __init__.py
    │   #    flags=test
    └── __main__.py
        #    import foldername
        #   
        #    def main():
        #        print foldername.flags
        #   
        #    if __name__==__main__:
        #        main()

If the parent directory for foldername is in your python path then you could run the above commands from any directory.

PYTHONPATH issue. Make sure that foldername is available in your path. If you are running it from inside foldername it might not be available. Try running from the parent of foldername.

Here is a question about finding your PYTHONPATH.

Python unable to import custom module despite having __init__.py

Make sure your layout is like this:

./folder/__init__.py
./main.py

and there is not file named folder.py!

Change to the parent folder, so that ls folder/__init__.py works.

Next try running python -c import folder.

Leave a Reply

Your email address will not be published. Required fields are marked *