【发布时间】:2013-02-24 16:16:41
【问题描述】:
我一直在尝试为我的程序实现 __import__() 和 reload() ,但没有成功。我有一个字符串,我将其写入 .py 文件(模块),然后将其作为模块加载。然后我对该 .py 文件(模块)进行更改并写入它,但我似乎无法在新更新的模块中更改返回值。这是我的代码:
str1 = '''
def run():
return 10
'''
f = open('mycode.py','w')
f.write(str1)
f.close()
mymodule = __import__('mycode')
es = 'number = mymodule.run()'
exec(es)
print "number", number
str2 = '''
def run():
return 99
'''
f = open('mycode.py','w')
f.write(str2)
f.close()
mymodule = reload(mymodule)
mymodule = __import__('mycode')
es = 'number = mymodule.run()'
exec(es)
print "number", number
OUTPUT:
>> number 10
>> number 10 # should be 99
我看过这里:Re-import the same python module with __import__() in a fail-safe way
这里:
reloading module which has been imported to another module
这里:
How do I unload (reload) a Python module?
但我无法提出解决方案。任何帮助,将不胜感激。谢谢。
保罗
编辑
我之所以使用 exec(es) 是因为如果我有多个参数,我想自定义 es。这是一个例子:
p = [2,1]
p2 = [3,4,5]
p3 = [100,200,300,500]
str1 = '''
def run(x,y):
return x + y
'''
with open('mycode.py','w') as f:
f.write(str)
import mycode as mymodule
# how do i do this dynamically,
# how to handle it when # of paremeters for run() change?
print mymodule.run(p[0],p[1]) # hard-coded parameter passing
# or, print mymodule.run(p[0],p3[1],p[2]) # if run() is changed
所以问题是我的 run() 可以有不同的参数。它可以是 run(x,y) 或 run(larry, moe, curly, hickory, dickory, dock)。如何动态地将多个参数传递给 run()?谢谢。
【问题讨论】:
-
我知道我没有回答这个问题,但如果你想在运行时创建新行为,这不是要走的路。在 Python 中,您可以在运行时重新定义和修补类,而无需
reload()。reload机制充其量是脆弱的——它适用于 REPL,而不是用于编程用途。 -
如果你真的想更换一个模块,你可以随时访问
sys.modules。这就是python-sh所做的,例如 -
同时,你为什么在这里使用
exec(es)而不仅仅是number = mymodule.run()?你期待它做一些不同的事情吗? (如果是,那是什么?)或者只是增加更多的复杂性以使问题变得更加困难? -
我正在使用 exec() 因为我希望能够更改 run() 的参数,例如运行(10,30)。我的解释中没有包含这一点。
-
调用具有动态数量参数的函数的处理方式很简单:执行
mymodule.run(*p)。如果有两个元素,那就是mymodule.run(p[0], p[1]),如果没有元素,那就是mymodule.run()。不需要exec。
标签: python