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
This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.
The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.
The gist is that __init__.py is used to indicate that a directory is a python package. (A quick note about packages vs. modules from the python docs: "From a file system perspective, packages are directories and modules are files.").
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.
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With