python reload error

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wzx479/article/details/84075091

1、Python2中可以和Python3中关于reload()用法的区别。Python2 中可以直接使用reload(module)重载模块。

Pyhton3中需要使用如下两种方式:
方式(1)

from importlib
imp.reload(module)
方式(2)

from importlib import reload
reload(module)

2、Python中使用import和reload()出现错误的原因

在Python中,以py为扩展名保存的文件就可以认为是一个模块,模块包含了 Python 对象定义和Python语句。

假设recommendations.py放在C:\Python34\PCI_Code\chapter2\目录下,其中包含函数critics
如果在import函数的时候出现如下错误:

from recommendation import critics
Traceback (most recent call last):
File “<pyshell#7>”, line 1, in
from recommendation import critics
ImportError: No module named ‘recommendation’
请把目录C:\Python34\PCI_Code\chapter2\加到系统路径中,

import sys
sys.path.append(“C:\Python34\PCI_Code\chapter2”)

from recommendations import critics

或者切换到文件所在的目录中,

C:\Python34\PCI_Code\chapter2>python
from recommendations import *


使用reload()时出现如下错误

from imp import reload
reload(recommendations)
Traceback (most recent call last):
File “<pyshell#86>”, line 1, in
reload(recommendations)
NameError: name ‘recommendations’ is not define

原因是因为在reload某个模块的时候,需要先import来加载需要的模块,这时候再去reload就不会有问题,具体看下面代码:

from imp import reload
reload(recommendations)
import recommendations
<module ‘recommendations’ from ‘C:\Python34\PCI_Code\chapter2\recommendations.py’>

猜你喜欢

转载自blog.csdn.net/wzx479/article/details/84075091