【问题标题】:Reload function usage in Python 3.3.2Python 3.3.2 中的重载函数用法
【发布时间】:2013-11-03 12:32:35
【问题描述】:

我读了很多关于 reload 的文章,但我无法使用 reload 功能。imp.py 本身有一些错误。我没有做任何更改。

>>> import imp
>>> imp.reload('fileread')
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    imp.reload('fileread')
  File "C:\Python33\lib\imp.py", line 258, in reload
    raise TypeError("reload() argument must be module")
TypeError: reload() argument must be module

fileread 存储在 python 的正确目录中。

【问题讨论】:

    标签: python python-3.x error-handling reload


    【解决方案1】:

    您需要将实际的模块对象传递给imp.reload()

    如果你只有模块name,在sys.modules mapping中查找模块对象:

    import sys
    import imp
    
    imp.reload(sys.modules['fileread'])
    

    这只适用于已经导入的模块;如果您的某些条目尚未导入,请至少抓住KeyError 跳过这些:

    try:
        imp.reload(sys.modules[modulename])
    except KeyError:
        # not loaded, no point in reloading
        pass
    

    您也可以选择使用importlib.import_module() 来加载此类模块。

    【讨论】:

    • >>> import sys >>> import imp >>> imp.reload(sys.modules['fileread']) Traceback(最近一次调用):文件“” ,第 1 行,在 imp.reload(sys.modules['fileread']) KeyError: 'fileread' 我仍然收到错误
    • @PavanRavishankar:那么模块没有导入。先导入fileread;此时也无需重新加载。
    猜你喜欢
    • 1970-01-01
    • 2015-10-19
    • 2011-10-30
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多