Python拾趣005 importlib之动态加载

Python作为当今最流行的脚本语言,动态编译执行是其最重要的特点。

我们可以在程序运行时,修改相关的代码再重新加载入主程序中。用到的

库是importlib。

importlib.reload()可以用来重载函数,importlib.import_module()可以加载函数。

代码如下:

test019module.py

"""
PyQt AND OpenCV
By LiNYoUBiAo
2020/4/4 17:57
"""
Name = "World"
Version = "0.2.0"
Description = "Try to Reload"

test019main.py

"""
PyQt AND OpenCV
By LiNYoUBiAo
2020/4/4 17:57
"""
import importlib
import sys
import test019module
from PyQt5.QtWidgets import (QApplication, QVBoxLayout, QDialog, QPushButton, QLabel)


class Form(QDialog):
    def __init__(self):
        super(Form, self).__init__()
        self.label = QLabel(self)
        self.label.setText("Version")
        self.button1 = QPushButton(self)
        self.button1.setText("See")
        self.button1.clicked.connect(self.clicked_button1)
        self.button2 = QPushButton(self)
        self.button2.setText("Reload")
        self.button2.clicked.connect(self.clicked_button2)
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.label)
        self.layout.addWidget(self.button1)
        self.layout.addWidget(self.button2)
        self.setLayout(self.layout)

    def clicked_button1(self):
        self.label.setText(str(test019module.Version))

    def clicked_button2(self):
        importlib.reload(test019module)
        self.label.setText(str(test019module.Name))


if __name__ == "__main__":
    app = QApplication(sys.argv)

    form = Form()
    form.show()

    sys.exit(app.exec_())

运行界面如下:

 

不关闭程序,修改一下test019module.py中的代码,把Version修改一下为0.3.1,保存,再按一下Reload键,

重新载入test019module,再See一下,如下:

可以见到,Version变了。

多谢,美。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值