Solution to import error of python custom package or module on Linux server
Run the python code on the local machine, there is no problem with the self-defined file to guide the package operation, but when it is placed on the linux server, it will prompt ImportError: No module named xxxx (the file package name to be imported)
There are three rules when importing python packages:
- 1. Strictly distinguish between packages and folders. The definition of a package is the folder containing __init__.py. If there is no __init__.py, then it is a normal folder.
- 2. Import the package. Create a new xxx.pth in the site-package folder of the python installation directory, the content is the folder path where the package to be imported is located.
- 3. Import the module. It is the general way of importing modules. Note that only the package path is required, not the folder path.
Solution:
- 1. Find your python installation path, mine is in /home/dgw/ env/lib/python2.7 to view the path method, please refer to the blog post, go back one level to find the lib path : https://blog.csdn .net/weixin_44799217/article/details/114046051
- 2. Enter the site-packages of the python installation path. That is: /home/dgw/env/lib/python2.7/site-packages
- 3. Create a file with a suffix of .pth: touch xxx.pth
- 4. Edit the pth file: vim xxx.pth
- 5. Write the absolute path of the package you want to import into the xxx.pth file. (Note: It must be an absolute path, and the package to be imported needs to have __init__.py file) [Right-click in pycharm to view the absolute path]
E.g:
/home/dgw/work/package(package是要导入的包)
Case 2:
Through sys.path.append('path to be imported')