Reference custom modules in Python
After learning Python for a short period of time, it has never been stuck in simple syntax and cannot really understand the power of Python. I learned how to reference a custom module today. When a module is referenced, the compiler will first find the referenced module in the current directory, and then go to the sys. path and Python installation directories. If not, an error will be reported.
In the first case, your module is in the same directory as the module you want to use. Hello. py is a module with the Hello, World printing method Hello (). Test. py is a test program that references the Hello () method in hello. py. It can be referenced directly because it is in the same directory as the module.
Hello. py
Def hello (): print "Hello World"
Test. py
Import HelloHello. hello ()
In the second case, the module is somewhere else. Method 1: first reference sys to modify sys. path. In fact, the module path is added to sys. path.
Test. py
Import syssys. path. append ('e:/workspace/Modules ') import HelloHello. hello ()
Method 2: add the path to the environment variable. This is permanent. You can create a folder for storing modules and add the path of this folder to the environment variable, it can work at a time, never causing trouble, and also facilitates management.