I have a folder with a __init__.py
File __init__.py:
#!/usr/bin/python2
flags="test"
File main.py:
#!/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 the error
ImportError: No module named foldername
4 Answers 4
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.
4 Comments
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".
2 Comments
PYTHONPATH issue. It is python path issue (sys.path). My PYTHONPATH environment variable is always empty. python implicitly adds script's directory to sys.path. Sometimes It is called sys.path[0] initialization for scripts.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".
Comments
If you want to import the a module in python3 simply go to the root folder
python3 -mModuleName
Make sure you do not remove the -m before the module name and then this you can import this module anywhere inside the project directory.
foldernameis in your python path (environment variablePYTHONPATH).flags- It should befoldername.flags.main. Andmain.pyshould not be inside the same folder.main.pymay be inside the same folder. Python 2.7 even supports it explicitly with__main__.pyname.