Python was not able to import the user module, despite the presence of __init__.py

I have a folder with __init__.py

__Init__.py file:

 #!/usr/bin/python2 flags="test" 

Main.py file:

 #!/usr/bin/python2 import foldername def main(): print foldername.flags if __name__ == '__main__': main() 

Now when I run ./main.py (from inside the folder), I get an error

 ImportError: No module named foldername 
+4
source share
3 answers

Run from parent folder for foldername :

 $ python -mfoldername.main 

If you rename main.py to __main__.py , you can run it like (since Python 2.7):

 $ python -mfoldername 

python -m adds the implicit 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, you can run the above commands from any directory.

+5
source

PYTHONPATH . Make sure the "folder name" is available in your path. If you use it inside the "folder name", it may not be available. Try running from the parent "foldername".

Here is a question about finding your PYTHONPATH .

+3
source

Make sure your layout looks like this:

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

and there is no file named folder.py !

Go to the parent folder for ls folder/__init__.py work.

Then try running python -c "import folder" .

+3
source

Source: https://habr.com/ru/post/1394249/


All Articles