Many beginners often encounter such problems , That is, customize Python After the template , Use... In other documents import( or from…import) When the statement is introduced into the file ,Python The interpreter also has the following errors :
ModuleNotFoundError: No module named ‘ Module name ’
intend Python The module name cannot be found , What is the cause of this ? To solve this problem , Readers should find out first Python The process of finding module files by the interpreter .
Usually , When using import After the statement is imported into the module ,Python The specified module files will be found in the following order :
All the directories involved above , All stored in the standard module sys Of sys.path variable , Through this variable, we can see all directories supported by the specified program file . let me put it another way , If the module to be imported is not stored in sys.path In the displayed Directory , When you import the module and run the program ,Python The interpreter will throw ModuleNotFoundError( Module not found ) abnormal .
solve “Python Specified module not found ” The way to do this is 3 Kind of , Namely :
however , In detail, this 3 Before we do that , In order to explain more conveniently , This section uses the hello.py Custom module file (D:\python_module\hello.py) and say.py Program files (C:\Users\mengma\Desktop\say.py, Located on the desktop ), They each contain the following code :
#hello.py
def say ():
print("Hello,World!")
#say.py
import hello
hello.say()
obviously ,hello.py Document and say.py The files are not in the same directory , At this time to run say.py file , The operation result is :
Traceback (most recent call last):
File "C:\\Users\\mengma\\Desktop\\say.py", line 1, in <module>
import hello
ModuleNotFoundError: No module named 'hello'
You can see ,Python The interpreter threw ModuleNotFoundError abnormal . Next , Use the above... Respectively 3 There are two ways to solve this problem .
Storage location of module files , Can be temporarily added to sys.path variable , That is to sys.path Add D:\python_module(hello.py In the directory ), stay say.py Add the following code at the beginning of the :
import sys
sys.path.append('D:\\python_module')
Be careful : In add full path , In the path ‘\’ Need to use \ Transference , Otherwise, it will lead to grammatical errors . Run again say.py file , The operation results are as follows :
Hello,World!
You can see , The program runs successfully . On this basis , We are say.py Output in file sys.path The value of the variable , You will get the following results :\['C:\\\\Users\\\\mengma\\\\Desktop', 'D:\\\\python3.6\\\\Lib\\\\idlelib', 'D:\\\\python3.6\\\\python36.zip', 'D:\\\\python3.6\\\\DLLs', 'D:\\\\python3.6\\\\lib', 'D:\\\\python3.6', 'C:\\\\Users\\\\mengma\\\\AppData\\\\Roaming\\\\Python\\\\Python36\\\\site-packages', 'D:\\\\python3.6\\\\lib\\\\site-packages', 'D:\\\\python3.6\\\\lib\\\\site-packages\\\\win32', 'D:\\\\python3.6\\\\lib\\\\site-packages\\\\win32\\\\lib', 'D:\\\\python3.6\\\\lib\\\\site-packages\\\\Pythonwin', 'D:\\\\python\_module'\]
In this output message , The red part is the temporarily added storage path . It should be noted that , Directories added by this method , Only valid in the window where the current file is executed , When the window is closed, it becomes invalid .
If you want to install some generic modules , For example, modules supported by complex functions 、 Matrix computing supported modules 、 Modules supported by graphical interface, etc , These belong to the right Python Modules that extend themselves , This module should be installed directly in Python Inside , To be shared by all programs , At this point, you can use Python The default module loading path .
Python The default module loading path of the program is saved in sys.path variable , therefore , We can do it in say.py First look at the program file sys.path The default load path saved in , towards say.py Output in file sys.path Value , As shown below :\['C:\\\\Users\\\\mengma\\\\Desktop', 'D:\\\\python3.6\\\\Lib\\\\idlelib', 'D:\\\\python3.6\\\\python36.zip', 'D:\\\\python3.6\\\\DLLs', 'D:\\\\python3.6\\\\lib', 'D:\\\\python3.6', 'C:\\\\Users\\\\mengma\\\\AppData\\\\Roaming\\\\Python\\\\Python36\\\\site-packages', 'D:\\\\python3.6\\\\lib\\\\site-packages', 'D:\\\\python3.6\\\\lib\\\\site-packages\\\\win32', 'D:\\\\python3.6\\\\lib\\\\site-packages\\\\win32\\\\lib', 'D:\\\\python3.6\\\\lib\\\\site-packages\\\\Pythonwin'\]
In the above run result , All the paths listed are Python The default module loading path , But generally speaking , By default, we will Python Add an extension module to lib\site-packages
Under the path , It is specially used to store Python Expansion modules and packages .
therefore , We can directly put what we have written hello.py Add files to lib\site-packages
Under the path , It's equivalent to Python Expanded one hello modular , So any Python Programs can use this module .
After the mobile work is completed , Run again say.py file , You can see the result of successful operation :
Hello,World!
PYTHONPATH environment variable ( abbreviation path Variable ) The value of is a collection of many paths ,Python The interpreter will follow path Search the included path once , Until you find the module specified to load . Of course , If you still don't find it in the end , be Python Report on ModuleNotFoundError abnormal .
Due to different platforms , Set up path The setting process of environment variables is different , So the next most used Windows、Linux、Mac OS X this 3 A platform , Show readers how to set up path environment variable .
First , Find the “ Computer ”( Or my computer ), And right click , single click “ attribute ”. This will show “ Control panel \ All control panel items \ System ” window , Click... In the left column of the window “ Advanced system setup ” menu , appear “ System attribute ” Dialog box , Pictured 1 Shown .
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-to5XHniU-1656314615077)(https://editor.csdn.net/uploads/allimg/190221/2-1Z22114355J96.gif)]
chart 1 System properties dialog box
Pictured 1 Shown , Click on “ environment variable ” Button , The chart will pop up 2 The dialog shown :
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-n3sQSoZ1-1656314615087)(https://editor.csdn.net/uploads/allimg/190221/2-1Z22114361X93.gif)]
chart 2 Environment variables dialog box
Pictured 2 Shown , Through this dialog , You can do it path Setting of environment variables . It should be noted that , The dialog box is divided into up and down 2 part , uppermost “ User variables ” Section is used to set the environment variables of the current user , Below “ System variables ” Part is used to set the environment variables of the whole system .
Usually , It is recommended that you set the user's path Variable can , Because this setting is only valid for the user currently logged in to the system , And if you modify the path Variable , Is valid for all users .
For ordinary users , Set user path Variables and systems path The effect of variables is the same , but Python In the use of path variable , Will first follow the system path Variable path to find , Then according to the user path Variable path to find .
Here we choose to set the current user's path Variable . Click... In the user variable “ newly build ” Button , The system will pop up as shown in the figure 3 The dialog shown .
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-7nME01Gi-1656314615088)(https://editor.csdn.net/uploads/allimg/190221/2-1Z221143645404.gif)]
chart 3 newly build PYTHONPATH environment variable
among , stay “ Variable name ” Input in text box PYTHONPATH, Indicates that a file named PYTHONPATH Environment variables of ; stay “ A variable's value ” Input in text box .;d:\python_ module
. Be careful , There are actually two paths here ( With a semicolon ; As a separator ):
d:\python_ module
, When running Python The program ,Python Will be available from d:\python_ module
Load module in . And then click “ determine ”, I.e. successfully set path environment variable . here , We just need to move the module file to the same directory as the file that introduced the module , Or move to d:\python_ module
Under the path , The module can be loaded successfully .
start-up Linux The terminal window of , Enter the current user's home Under the path , And then in home Enter the following command under the path :
ls - a
This command will list all the files in the current path , Including hidden files .Linux The environment variables of the platform are through .bash_profile File to set , Open the file using the unformatted editor , Add... To the file PYTHONPATH environment variable . That is, add the following line to the file :
# Set up PYTHON PATH environment variable
PYTHONPATH=.:/home/mengma/python_module
Linux And Windows The platform is different , Colon between multiple paths (:) As a separator , So the above line also sets two paths , spot (.) Represents the current path , Another path is /home/mengma/python_module
(mengma Is in Linux The login name of the system ).
At the completion of the PYTHONPATH After setting the variable value , stay .bash_profile Add export at the end of the file PYTHONPATH Variable statement .
# export PYTHONPATH environment variable
export PYTHONPATH
Log back in Linux platform , Or execute the following command :
source.bash_profile
Both methods are used to run the file , Set in the file PYTHONPATH Variable values take effect .
After successfully setting the above environment variables , Next, just add the module defined above (Python Program ) Put it in the same place as the current operation Python In the same path as the program ( Or put it in /home/mengma/python_module
Under the path ), The module can be loaded successfully .
stay Mac OS X Set the environment variables on the Linux Almost the same ( because Mac OS X Itself is also a class UNIX System ). start-up Mac OS X The terminal window of ( Command line interface ), Enter the current user's home Under the path , And then in home Enter the following command under the path :
ls -a
This command will list all the files in the current path , Including hidden files .Mac OS X The environment variables of the platform can also be accessed through ,bash_profile File to set up , Open the file using the unformatted editor , Add... To the file PYTHONPATH environment variable . That is, add the following line to the file :
# Set up PYTHON PATH Environment variable disk
PYTHONPATH=.:/Users/mengma/python_module
Mac OS X The same colon is used between multiple paths of (:) As a separator , So the above line also sets two paths : spot (.) Represents the current path , Another path is /Users/mengma/python_module
(memgma It's the author Mac OS X The login name of the system ).
At the completion of the PYTHONPATH After setting the variable value , stay .bash_profile Add export at the end of the file PYTHONPATH Variable statement .
# export PYTHON PATH environment variable
export PYTHONPATH
Log back in Mac OS X System , Or execute the following command :
source.bash_profile
Both methods are used to run the file , Set in the file PYTHONPATH Variable values take effect .
After successfully setting the above environment variables , Next, just add the module defined above (Python Program ) Put it in the same place as the current operation Python In the same path as the program ( Or put it in Users/mengma/python_module
Under the path ), The module can be loaded successfully .