The introduction
When we import OS, improt SYS, Improt Math, etc., we can import them successfully, but when we import AAA, we can’t. That’s because of Python’s package path. Let’s look at Python’s package path and see how it works.
View the packet guide path
You can view the packet guide path using the built-in SYS module.
In [1] :import sys
In [2]: sys.path
Out[2] : ['D:\\Hui\\DevelopEnv\\Python\\Python379\\Scripts\\ipython.exe'.'d:\\hui\\developenv\\python\\python379\\python37.zip'.'d:\\hui\\developenv\\python\\python379\\DLLs'.'d:\\hui\\developenv\\python\\python379\\lib'.'d:\\hui\\developenv\\python\\python379'.' '.'d:\\hui\\developenv\\python\\python379\\lib\\site-packages'.'d:\\hui\\developenv\\python\\python379\\lib\\site-packages\\IPython\\extensions'.'C:\\Users\\Administrator\\.ipython']
In [3] :Copy the code
Sys. path returns a list of paths that represent the paths of the search elements used to guide Python packages.
- The Python interpreterfrom
sys.path
In order to find the module file or package to import ' '
Represents the current pathsys.path
The order of the paths in the list representsThe Python interpreterThe order in which modules are searched
Path for storing built-in modules and packages
Built-in modules and packages like OS, SYS, JSON, etc., are stored in the Lib directory where the Python interpreter was saved when you downloaded it
Storage path to my personal example:
D:\Hui\DevelopEnv\Python\Python379\Lib
Copy the code
Download the third party inventory path
Self-downloaded third-party libraries like Requests and ipython are stored in the Lib site-packages directory
Storage path to my personal example
D:\Hui\DevelopEnv\Python\Python379\Lib\site-packages
Copy the code
However, sys.path contains both paths
So we can find modules and packages using import OS, import sys, import JSON, import requests, and so on
If the corresponding module is not found in sys.path when importing modules and packages, the following error is reported
ModuleNotFoundError: No module named 'xxx'
Copy the code
import aaa
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-4-37ad1770aa41> in <module>
----> 1 import aaa
ModuleNotFoundError: No module named 'aaa'
Copy the code
It works a bit like our computer’s environment variable -Path.
You can open the Python interactive interpreter by typing Python in a CMD window. PIP install XXX can download third-party libraries. All because of the system environment variable -path, which has a specific executable file Path
Append a new packet guide path
We can append a new package path dynamically while the program is running, as shown below
sys.path.append('D:\Hui\Code\Python\demo') # append to end
sys.path.insert(0.'D:\Hui\Code\Python\demo') Append to the beginning position to ensure that the path is searched first
Copy the code
Ipython test
There is now a aaa.py module in the D:\Hui\Code\Python\demo directory.
The aaA.py module contains the following contents
# aaa.py
def test() :
print('Succeeded in adding guide path')
Copy the code
[bug Mc-108966] – Import AAA fails to append D:\Hui\Code\Python\demo to package path
After appending, try again
After adding the guide package path can be successfully imported and used.
Django projects append package paths
Come to the application scenario of kangkang guide packet path.
Django usually places subapplication modules under the apps package, but how do you set the path when registering subapplications?
Add code to print the guide path in settings.pyordevelop.py
import sys
from pprint import pprint
pprint(sys.path)
Copy the code
Pprint pretty print so that the list of outputs is not on one line.
Then run the Django program to see the package path results
['C:\\Users\\Administrator\\Desktop\\meiduo_project\\meiduo_mall'.'C:\\Users\\Administrator\\Desktop\\meiduo_project'.'D:\\Hui\\DevelopTools\\PyCharm '
'2020.2.3 \ \ \ \ plugins \ \ python helpers \ \ pycharm_display'.'d:\\hui\\developenv\\python\\python379\\python37.zip'.'d:\\hui\\developenv\\python\\python379\\DLLs'.'d:\\hui\\developenv\\python\\python379\\lib'.'d:\\hui\\developenv\\python\\python379'.'D:\\Hui\\VirtualEnv\\meiduo_mall'.'D:\\Hui\\VirtualEnv\\meiduo_mall\\lib\\site-packages'.'D:\\Hui\\DevelopTools\\PyCharm '
'2020.2.3 \ \ \ \ plugins \ \ python helpers \ \ pycharm_matplotlib_backend']
Copy the code
We know the guide path
meiduo_project/meiduo_mall
The directory where the Users application resides is known
meiduo_project/meiduo_mall/meiduo_mall/apps/users
Therefore, the path to import the Users application can be written as meiduo_mall/apps/users
Knowing where the package is going is a good way to register the child application in settings.pyordevelop.py
INSTALLED_APPS = [
'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.'meiduo_mall.apps.users'.# Register user module
]
Copy the code
Is it possible to make registering users applications easier? Use the following format to register with the application name Users
INSTALLED_APPS = [
'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.'users'.# Register user module
]
Copy the code
Analysis:
- We know the guide path
meiduo_project/meiduo_mall
- known
users
Application Directorymeiduo_project/meiduo_mall/meiduo_mall/apps/users
- To use the application name directly
users
registered- A guide path is required:
meiduo_project/meiduo_mall/meiduo_mall/apps
- A guide path is required:
The solution
- Append guide path:
meiduo_project/meiduo_mall/meiduo_mall/apps
Append the guide path to settings.pyordevelop.py
sys.path.insert(0.r'meiduo_project/meiduo_mall/meiduo_mall/apps/users')
Copy the code
Dead paths are not written in projects, so use BASE_DIR to dynamically concatenate paths
The BASE_DIR content is displayed as follows
'C:\\Users\\Administrator\\Desktop\\meiduo_project\\meiduo_mall\\meiduo_mall'
Copy the code
Where does that path come from? Let’s look at the code, okay
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Copy the code
- Among them
__file__
Is to point to the current module os.path.abspath(__file__)
Is the absolute path to the current moduleos.path.dirname(os.path.abspath(__file__))
Obtain the directory where the module resides according to the current module path
Therefore:
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Copy the code
This is the directory above which the current module resides.
The current module in my case is develop.py, which is in Settings, and the directory above Settings is meiduo_mall
Therefore, we can add the packet guide path through BASE_DIR dynamic concatenation of paths
Append the subapplication package path
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
Copy the code
Register the child application and write the application name directly.
INSTALLED_APPS = [
'django.contrib.admin'.'django.contrib.auth'.'django.contrib.contenttypes'.'django.contrib.sessions'.'django.contrib.messages'.'django.contrib.staticfiles'.# 'meiduo_mall.apps.users'
'users'
]
Copy the code
The role of guide packet paths
By viewing the package guide path, you can quickly know how to import each package in the project.
When taking over the project, I can adapt to the way of project guide package as soon as possible.
By adding packet guide paths, you can simplify the complicated packet guide mode of some directories.
Re-import modules
After the module is imported, import Module can not re-import the module, re-import must use IMP reload
from imp import reload
Copy the code
Let’s go back to the aaA.py module example I mentioned earlier
# aaa.py
def test() :
print('Succeeded in adding guide path')
Copy the code
Ipython test
In [21] :import aaa
In [22]: aaa. Test () succeeded In adding the packet guide path In [23] :Copy the code
Do not close ipython at this point and then modify the aaA.py module as follows
# aaa.py
def test() :
print('Reimport module tests')
Copy the code
Then go back to ipython to test
# Before modification
In [21] :import aaa
In [22]: aaa.test() Succeeded in adding the packet guide path# after modification
In [23]: aaa. Test () succeeded In adding the packet guide path In [24] :import aaa
In [25]: aaa. Test () succeeded In adding the packet guide path In [26] :Copy the code
Aaa. Py has been modified, but the current ipython interaction does not know about it. We can open another ipython interaction to verify this
In [3] :import sys
My aaa. Py module is not in the current package path, so I need to append it dynamically
In [4]: sys.path.insert(0.'D:\Hui\Code\Python\demo')
In [5] :import aaa
In [6]: aaa.test() re-import the module test In [7] :Copy the code
Therefore, after the AAA module is imported, import AAA cannot import the module again. Use the following method to import the module again
# Before modification
In [21] :import aaa
In [22]: aaa.test() Succeeded in adding the packet guide path# after modification
In [23]: aaa. Test () succeeded In adding the packet guide path In [24] :import aaa
In [25]: aaa. Test () succeeded In adding the packet guide path In [27] :from imp import reload
In [28]: reload(aaa)
Out[28]: <module 'aaa' from 'D:\\Hui\\Code\\Python\\demo\\aaa.py'>
In [29]: aaa.test() reimports module testsCopy the code
✍ code word is not easy, the long journey always feeling, praise again go line, also hope you heroes support ❤️
The public,
Create a new folder X
Nature took tens of billions of years to create our real world, while programmers took hundreds of years to create a completely different virtual world. We knock out brick by brick with a keyboard and build everything with our brains. People see 1000 as authority. We defend 1024. We are not keyboard warriors, we are just extraordinary builders of ordinary world.