No module named xxx

No module named xxx
can run normally in Pycharm, but an error is reported when running through the command line

The error means that the xxx module cannot be found, but there is a file xxx.py in our project.

When Pycharm executes, it will search the directory of the entire project, so it can be found.
Command line execution does not retrieve the entire project.

So we need to manually add the search path to it

import os
import sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

The above code just adds the upper-level directory of the file to the search directory. If the root directory of the project is not the directory, you can continue to search the upper-level directory through os.path.dirname() until the root directory of the project.

Guess you like

Origin blog.csdn.net/m0_37690430/article/details/125990626