解决Python运行脚本时ModuleNotFoundError: No module named 'xxx'报错

发布时间 2023-03-22 21:08:47作者: IdaW

自己写的项目直接在Pycharm里run或debug没问题,但使用cmd命令通过python xxx.py运行脚本,如果脚本import了其他文件的方法就会报错:ModuleNotFoundError: No module named 'xxx'。

例如:

项目auto_test结构:

├──conf.py  # 配置文件
└──api      
│ ├── testcases

│ │ ├── test_api.py  

在test_api.py里from conf import *,在cmd里运行 python auto_test/api/testcases/test_api.py就会报ImportError错。

解决方法

在import之前把conf.py所在目录路径添加到sys.path里。

test_api.py

import os, sys

curPath = os.path.dirname(__file__) # 获取test_api.py文件所在目录路径
sys.path.append(curPath+'/../../')  # 根据conf.py与test_api.py的相对路径添加到sys.path

from conf import *
...

注意自己项目的目录结构,根据自己的情况添加。