简体   繁体   English

如何在Python控制台中重新加载模块?

[英]How do I reload a module in the Python console?

I'm using PyCharm with Python 3.7. 我在Python 3.7中使用PyCharm。 In my Python console, how do I reload a module that I've changed? 在我的Python控制台中,如何重新加载已更改的模块? I created a file, "services.py" where I created a service class in 我创建了一个文件“ services.py”,在其中创建了一个服务类

class ArticlesService:
    def process(self):

As I test this in the console, I can't seem to figure out how to reload it. 当我在控制台中对此进行测试时,我似乎无法弄清楚如何重新加载它。 This is the error I get 这是我得到的错误

from mainpage.services import ArticlesService
importlib.reload(ArticlesService)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 140, in reload
    raise TypeError("reload() argument must be a module")
TypeError: reload() argument must be a module

How do I refer to my class to reload it? 如何引用我的班级来重新加载它? (Or better yet, how do I get the console to automatically reload everything I've changed?) (或者更好的是,如何使控制台自动重新加载已更改的所有内容?)

from mainpage.services import ArticlesService only imports the class into your namespace, so you have no reference to the module in the namespace. from mainpage.services import ArticlesService仅将类导入您的名称空间,因此您没有对名称空间中的模块的引用。 From the importlib.reload docs: importlib.reload文档:

Reload a previously imported module . 重新加载先前导入的模块 The argument must be a module object, so it must have been successfully imported before. 参数必须是模块对象,因此它必须已经成功导入。

So make sure to import the module if you want to reload later: 因此,如果要稍后重新加载,请确保导入模块:

import importlib
import mainpage
from mainpage.services import ArticlesService

...

importlib.reload(mainpage)

This should work as well: 这也应该工作:

import importlib
import mainpage.services
from mainpage.services import ArticlesService

...

importlib.reload(mainpage.services)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM