行则将至

人生在勤,不索何获

0%

Python Import module from different directory

Method 1: Import module from different directory by append sys.path

We can use sys.path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn’t find the module in its current directory. As sys.path falls under the list type class so, we can easily use the insert method to add the folder path.

1
2
3
4
import os
import sys
import_root_path = os.path.abspath('import/root/path/')
sys.path.append(import_root_path)

Method 2: Using the PYTHONPATH environment variable

if you don’t want to use the sys module to set the path of the new directory. You can assign a directory path to the PYTHONPATH variable and still get your program working.

  • In Linux, we can use the following command in the terminal to set the path:
1
export PYTHONPATH=’path/to/directory’  
  • In the Windows system :
1
SET PYTHONPATH=”path/to/directory”  

To see if the PYTHONPATH variable holds the path of the new folder, we can use the following command:

1
echo $PYTHONPATH

注意:

  • 把项目根目录加入环境变量(手动或通过脚本)
  • import 导入路径以项目根目录下的源码目录 src 为起始

参考:

Backlinks: