为python添加模块路径
├── Ipy │ ├── bin │ │ ├── bin.py │ │ └── __init__.py │ ├── test │ │ ├── calculation.py │ │ ├── date20180422.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ ├── calculation.cpython-36.pyc │ │ └── __init__.cpython-36.pyc
有如上文件路径,执行文件为bin.py,被调用文件是calculation.py模块。
计划在bin文件中加入from test import calculation 语句来导入被调用文件中的方法,那么如何让python能够识别到test这个目录的路径呢?我们只需要让Python能够找到Ipy目录,就自然能够找到它下面的test的目录。
1、通过__file__获取当前的文件名:bin.py
2、通过os.path.abspath(__file__)获取文件的绝对路径:../bin/bin.py
3、通过os.path.dirname()方法可以获取到文件目录的路径:../bin
4、再次通过os.path.dirname()获取Ipy目录的绝对路径
5、将获取的Ipy目录的绝对路径加入到python环境变量中,通过sys.path.insert()方法,加到系统路径的开始位置,测试用append方法追加在最后无法成功。
路径测试代码:
1 import sys, os 2 3 print('执行文件是 %s' % __file__) 4 f_name = os.path.abspath(__file__) 5 print('执行文件的绝对路径: ', f_name) 6 d_name = os.path.dirname(f_name) 7 print("执行文件的目录的绝对路径是: ", d_name) 8 f_d_name = os.path.dirname(d_name) 9 print("与被调用文件的目录的上一级目录绝对路径:", f_d_name)
添加路径:
1 import sys, os 2 3 # 根据os.path.abspath(__file__)获取当前文件的绝对路径 4 # 通过os.path.dirname()获取当前文件目录的绝对路径 5 6 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 7 8 # sys.path.append(BASE_DIR) append方法在linux下会报错 9 # print(sys.path) 10 # 采用insert的列表插入方法,将获取的文件夹路径临时的添加到文件路径列表中 11 sys.path.insert(0, BASE_DIR) 12 from test import calculation 13 14 res = calculation.add(1, 2) 15 print(calculation.add(1, 2))

浙公网安备 33010602011771号