手动配置Path的Python环境无法识别同目录src模块求助
问题:独立版Python无法识别同目录下的src模块
两台Windows机器,通过安装程序正常安装Python的机器上脚本可正常运行;但使用独立版Python并手动将安装目录添加到系统Path变量的机器上,脚本无法识别同目录下的src模块。
文件结构
project/ run_generator.py src/ __init__.py generator.py
run_generator.py代码
import os import traceback from time import time from src.generator import Generator if __name__ == "__main__": try: open_output_file = False # Set to True to open the output file automatically, False otherwise sort_adm_type_to_field_keys = False # Set to True to sort the match_adm_type_to_field keys, False otherwise script_path = os.path.abspath(__file__) script_dir = os.path.dirname(script_path) os.chdir(script_dir) start_time = time() generator = Generator(sort_adm_type_to_field_keys=sort_adm_type_to_field_keys) generator.generate_output(open_output_file=open_output_file) print(f"Execution time: {time() - start_time} seconds") except Exception as error: print(f"An error occurred: {error}") traceback.print_exc() if not os.getenv('PYCHARM_HOSTED'): input("Press Enter to exit")
报错信息
从run_generator.py所在目录执行python run_generator.py,出现以下错误:
Traceback (most recent call last): File "D:\Scripts\adm_inactivator_generator\run_generator.py", line 5, in <module> from src.generator import Generator ModuleNotFoundError: No module named 'src'
解决方案
方案1:手动添加脚本目录到Python路径
在导入src模块前,将脚本所在目录加入sys.path,修改后的代码开头如下:import os import sys import traceback from time import time # 把脚本所在目录添加到Python模块搜索路径 script_path = os.path.abspath(__file__) script_dir = os.path.dirname(script_path) sys.path.append(script_dir) from src.generator import Generator独立版Python可能未自动将当前工作目录加入
sys.path,手动添加后即可识别同目录模块。方案2:使用相对导入并调整运行方式
将导入语句改为相对导入:from .src.generator import Generator此时需将project作为包运行,在project的上级目录执行命令:
python -m project.run_generator方案3:设置PYTHONPATH环境变量
在Windows系统中添加系统环境变量PYTHONPATH,值设为project目录的绝对路径(如D:\Scripts\adm_inactivator_generator),设置后重启终端再运行脚本即可。
内容的提问来源于stack exchange,提问作者machadinhos
相关产品推荐
相关产品推荐

