在终端无法运行是因为在python解释下 中运行他只会读取sys.path下已有路径,项目路径没有在sys.path下添加进去所以找不到,
只需要把我们项目追加到sys.path的路径下就好了,需要在python的包下添加init.py文件来确定当前文件夹是一个python的包.
# coding=utf-8
import os
import sys
def _get_project_root_path(root_path=None):
"""
获取项目根目录路径
:param root_path:
:return:
"""
if root_path is None:
# root_path = env_dist.get('DG_SERVICE_ROOT_PATH')
# 设置文件跟目录路径
root_path = '/Users/xxx/Documents/xxx/xxx/xxx/' # 项目路径
if root_path is None:
root_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
return root_path
_get_project_root_path()
def append_sys_path(root_path=None):
"""
递归添加项目下所有的Package路径.
:return:
"""
pro_dir = _get_project_root_path(root_path)
result_dir = [pro_dir]
while result_dir:
single_dir = result_dir.pop()
init_flag = False
subdir_list = []
for single_path in os.listdir(single_dir):
if single_path == '__init__.py':
init_flag = True # 根据当前目录是否存在__init__.py文件判断是否为package.
single_path = os.path.join(single_dir, single_path)
if os.path.isdir(single_path):
subdir_list.append(single_path)
if init_flag:
sys.path.append(single_dir)
result_dir.extend(subdir_list)
append_sys_path()
网友评论