Custom module introduction failed ModuleNotFoundError: No module named '****';

Cause of failure

After personal practice, I found that the reasons for the failure of custom modules are as follows:

1. The current path is not the path to the python import file or module by default.

2. There are problems with the self-made module itself. For example, due to some reasons, there is an error in compiling py into a pyd file and the python environment cannot recognize it.

3. There is a difference between the python version of the custom module and the currently used python

solution:

1. The path is not the default reference path

Get the path of the current file and add the current path to the path of the python import file

import sys, os
base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_path)
#----------------  sys拼接 一定要在自定义包引入之前定义   ----------------------------------
import package.test1 as test1       #注意import的顺序。
print(test1.a)

2. There is a problem with the method of compiling pyd files

The following is an effective method for compiling pyd files and personally testing it.

2.1 Change the suffix of the file to be compiled from .py to .pyx

Original file content

def ZWHp():
    print("Z_W_H_")
def ZWHp1():
    print("调用pyd")
def ZWHp2():
    print("Z_W_H_")

Modify suffix

2.2 Download the easycython module

pip install easycython

2.3 Use the conda environment of the python version to be used later, enter the command

Enter the specified folder, otherwise the produced files will be in other files

Enter the command

easycython ***.pyx

 If the red content is displayed, it means the compilation is successful.

2.4 Modify the name of the compiled pyd file

Modify as follows

Delete original files to prevent errors from being introduced

2.5 Introduce the pyd module and compile it, but the module will have red wavy lines. We can ignore it by right-clicking.

Original usage method: (further verification is required)

Use the cython module to compile py files into pyd files

3. The versions used to compile other python files are inconsistent

For example, if the python version to be used in the future is 3.9, then you cannot use version 3.10 to compile the file.

references

Python Getting Started Series 15 - The most detailed explanation of package and module import in history - Light Knowledge

2021-6-30: How to compile python files into pyd files_turn py into pyd-CSDN blog

Guess you like

Origin blog.csdn.net/qq_39397927/article/details/135090286