在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()
输出: