python中重新导入模块

        在python程序中,有一段for循环的数目会由传入参数来确定,本来是想用exec来执行一段动态代码来执行的,但结果并不如意,会出现没有定义变量的错误,由于在exec里用到的变量比较多,采用如下的方法并不好使:在局部变量域中执行代码

后来想到一个方法是动态生成一个py源文件,里边的内容可以根据变量进行生成。在使用的地方直接导入就可以了。

with open("genclass.py", 'w', encoding='utf-8') as f:
	f.write("from sympy import *\n\n")
	f.write("def hello_world():\n")
	f.write("\tprint('你好中国')\n")
	f.write("\tprint('你好法国')\n")
	
import  genclass
genclass.hello_world()

生成结果如下:

现在问题又来了,如果我生成的py文件又改了,怎么办?如果像如下这样写的话,出来的并不是我们想看到的结果:

	with open("genclass.py", 'w', encoding='utf-8') as f:
		f.write("from sympy import *\n\n")
		f.write("def hello_world():\n")
		f.write("\tprint('你好中国')\n")
		f.write("\tprint('你好法国')\n")
	
	import  genclass
	genclass.hello_world()
	
	with open("genclass.py", 'w', encoding='utf-8') as f:
		f.write("from sympy import *\n\n")
		f.write("def hello_world():\n")
		f.write("\tprint('你好中国1')\n")
		f.write("\tprint('你好法国2')\n")
	
	import  genclass
	genclass.hello_world()

输出:

并没有发生任何变化,原因是import包时,只默认导入一次,如果需要对一个包再次导入的话直接用import是无效的,好在python3提供了一个importlib库,里面提供了reload的方法,调用一次reload,可以把已经改变的包重新加载。代码如下:

    import importlib
	
    with open("genclass.py", 'w', encoding='utf-8') as f:
		f.write("from sympy import *\n\n")
		f.write("def hello_world():\n")
		f.write("\tprint('你好中国')\n")
		f.write("\tprint('你好法国')\n")
	
	import  genclass
	genclass.hello_world()
	
	with open("genclass.py", 'w', encoding='utf-8') as f:
		f.write("from sympy import *\n\n")
		f.write("def hello_world():\n")
		f.write("\tprint('你好中国1')\n")
		f.write("\tprint('你好法国2')\n")
	
	importlib.reload(genclass)
	genclass.hello_world()

输出:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值