起因:这两天运行需要用命令行来运行python文件,但是总是报错ModuleNotFoundError: No module named 'xxx'
(tf) liushanlin@liushanlindeMacBook-Air train % ~/miniforge3/envs/tf/bin/python3 resnet_cifar.py --checkpoints output/checkpoints
Traceback (most recent call last):
File "resnet_cifar.py", line 7, in <module>
from cnn.resnet.model.resnet import ResNet
ModuleNotFoundError: No module named 'cnn'
在网上找了一下,原因是解释器的搜索路径中没有要引用的包所在的路径,需要把这个路径加到sys.path中去
ps:记得确认一下命令行运行的python解释器是正确的,有时候命令行直接敲出来的python命令,使用的解释器的系统默认的解释器
步骤一:
>>> import os
>>> import sys
# __file__是要导入的文件名
>>> curPath = os.path.abspath(os.path.dirname("__file__"))
>>> rootPath = os.path.split(curPath)[0]
>>> print(root_path)
/Users/liushanlin/PycharmProjects/gan_mnist
>>> sys.path.append(new_path)
# 查看了一下发现已经加进去了
>>> print(sys.path)
['', '/Users/liushanlin/miniforge3/envs/tf/lib/python38.zip', '/Users/liushanlin/miniforge3/envs/tf/lib/python3.8', '/Users/liushanlin/miniforge3/envs/tf/lib/python3.8/lib-dynload', '/Users/liushanlin/miniforge3/envs/tf/lib/python3.8/site-packages', '/Users/liushanlin/PycharmProjects/gan_mnist']
>>> exit()
然后退出,再次运行发现又报错,还是没能找到。
再次从命令行进入python,查看发现刚才添加的路径居然不见了!
>>> import os
>>> import sys
>>> curPath = os.path.abspath(os.path.dirname("__file__"))
>>> rootPath = os.path.split(curPath)[0]
>>> print(root_path)
/Users/liushanlin/PycharmProjects/gan_mnist
>>> sys.path.append(new_path)
>>> print(sys.path)
['', '/Users/liushanlin/miniforge3/envs/tf/lib/python38.zip', '/Users/liushanlin/miniforge3/envs/tf/lib/python3.8', '/Users/liushanlin/miniforge3/envs/tf/lib/python3.8/lib-dynload', '/Users/liushanlin/miniforge3/envs/tf/lib/python3.8/site-packages']
>>> exit()
然后查了一下发现,每次进入python中添加的path都只是暂时生效,一旦退出就会失效。
于是,找到了以下解决方案:
步骤二:
>>> import sys
>>> print(sys.path)
['', '/Users/liushanlin/miniforge3/envs/tf/lib/python38.zip', '/Users/liushanlin/miniforge3/envs/tf/lib/python3.8', '/Users/liushanlin/miniforge3/envs/tf/lib/python3.8/lib-dynload', '/Users/liushanlin/miniforge3/envs/tf/lib/python3.8/site-packages']
这是系统默认的寻找包的路径,在其中任意一个包目录下创建"xxx.pth"文件,在.pth文件中写入要添加的路径,重新进入python解释器即可生效。
假如我们选择/Users/liushanlin/miniforge3/envs/tf/lib/python3.8/site-packages
这个目录,具体操作如下:
cd /Users/liushanlin/miniforge3/envs/tf/lib/python3.8/site-packages
vim project_path.pth
写入我们要导入的包所在目录
重新进入python解释器
>>> import sys
>>> print(sys.path)
['', '/Users/liushanlin/miniforge3/envs/tf/lib/python38.zip', '/Users/liushanlin/miniforge3/envs/tf/lib/python3.8', '/Users/liushanlin/miniforge3/envs/tf/lib/python3.8/lib-dynload', '/Users/liushanlin/miniforge3/envs/tf/lib/python3.8/site-packages',
'/Users/liushanlin/PycharmProjects/gan_mnist']
可以看到已经生效。
如果上面的回答对你有所帮助,请帮博主点个赞!谢谢!创作不易!