python introduces instances of importing custom modules and external files

  • 2020-06-12 09:51:44
  • OfStack

Do you want to use previous code in your project, or what requirements cause you to import external packages

If it's web, say, django, then you create a new app, write everything you need to import into this app, and then add app to ok

If it's native code, there are several ways to do it,

1. The simplest, and probably least useful, is to put your external files in the same package and directory as the files that need to be called

folder

------toinvoke.py

------tobeinvoded.py

This is introduced in ES25en.py

import toveinvoked or from tobeinvoked import *

Can be

2. Your other files are not single files, or cannot be placed in the same directory as mentioned above, but in different directories, subdirectories

folder

------tobeinvodedA.py

------tobeinvodedB.py

------tobeinvodedC.py

toinvoke.py

In this case, create a new, empty file with each folder ___. folder is no longer a plain folder, it's a package package, and it looks like this

The folder # folder now has the property of 1 python package package

------__init__.py

------tobeinvoded.py

------tobeinvodedA.py

------tobeinvodedB.py

------tobeinvodedC.py

toinvoke.py

This was introduced in ES85en.py

import toveinvoked or from folder import *

Can be

3. Similarly, if a module in folderB calls a module in folderA by the same method as above, what changes have you made

folderA

------tobeinvoded.py

------tobeinvodedA.py

------tobeinvodedB.py

------tobeinvodedC.py

folderB

--------toinvoke.py

This is introduced in ES127en.py

import folder or from folder *

Can be

4. Copy the code to $PYTHONHOME$\Lib\ ES144en-ES145en, just like the Eclipse plug-in installation

5. Under $PYTHONHOME$\Lib\ site-ES154en, create a new.pth file, say MyPackage.pth, which contains the absolute path to your package: E:/PythonPrj

Then, all packages under E:/PythonPrj can be introduced in the relative path of the package, which is similar to the link plug-in installation

6, with the above almost, can also add an environment variable, this is not to say more

To summarize, take a look at the Python packet search path

Python searches for the module it is looking for in the following path:

1. The folder where the program is located

2. Standard library installation path

3. The path contained in the operating system environment variable PYTHONPATH

There are two ways to add a custom library path to the Python library path:

1. Add library path dynamically. Modify the value of sys.path to add your own library path while the program is running

import sys

sys.path.append(r'your_path')

2. Create a.pth file in the folder \Lib\ site-ES199en under the Python installation directory, with the contents of the library path written by yourself. The sample is as follows

E:\\work\\Python\\http

E:\\work\\Python\\logging


Related articles: