When writing python, sometimes a python file may need to be used by other Python files, so you can import the package by importing it as follows:
1. Where do you put your own bag?
>>> import sys>>> sys.path[', '/usr/lib64/python34.zip ', '/usr/lib64/python3.4 ', '/usr/lib64/ Python3.4/plat-linux ', '/usr/lib64/python3.4/lib-dynload ', '/usr/lib64/python3.4/site-packages ', '/usr/lib/ Python3.4/site-packages ']
You can see some of the folder address listed above, then the package you write can theoretically put in the above address, but there are some such as "/usr/lib64/python3.4" is not recommended, the more recommended is: "", "'/usr/lib/python3.4/ Site-packages ' "," '/usr/lib64/python3.4/site-packages ' "
2. How do I import a package I wrote?
For example "/usr/lib/python3.4/site-packages", if I wrote a exp.py file under this file, then I write in my own system Python3 file can be used import exp Import.
You can also see that there is a "", and the current folder, if there is such a file structure:
parent/ one/
__init__.py exp.py exp2.py exp3.py
Both exp.py and exp2.py are in the one directory, so you can import the exp.py in exp2.py by using Import exp .
The exp3.py and one are in the parent directory, so you can import exp.py in exp3.py by importing one.exp
The role of 3.__init__.py
Occasionally you can see that some people write the package below there will also be a __init__.py, its role is to import the package first executed.
Assuming that import one.exp is written in exp3.py, the __init__.py file is executed first, and then the exp.py file is executed
If not, __init__.py can be empty, or you can simply not join __init__.py
4.if __name__ = = "__main__"
And sometimes you see. if __name__ = = "__MAIN__" statement, its role is to execute the program in the IF statement block when this file is not used as an imported file.
If exp.py is added if __name__ = = "__main__" and then python3 exp.py, the contents of this statement block will be executed.
If the If __name__ = = "Exp"is the part that is executed when the other file is imported with "Import exp"
If it is an if __name__ = = "One.exp", the part that is executed when the other file is imported with "Import One.exp"
note that the "import exp" is not executed if the contents of the If __name__ = = "One.exp"! Similarly: "Import one.exp" is not executed if the contents of the If __name__ = = = "Exp"
Python Import your own package