我正在编写一个脚本,并使用-i参数运行它,以便在repl完成后保持打开状态,以便能够在调试时查看有关我正在使用的对象的信息。
为了避免退出并重新运行脚本,我想我可以修改并保存脚本,然后导入script-name,然后使用script-name.main-method调用我的main方法。
现在我想写一个单字符的方法(为了方便),它可以:
def x():
import [this script]
[this script].[main-method]()而且还能够更改脚本的文件名,并保留易于重新加载的功能,而不必更改代码。
我试过使用importlib (见下文),但没有用。
def y():
import importlib
this = importlib.import_module("".join(sys.argv[0].split(".py"))) # sys.argv[0] gives [module-name].py and the rest of the code inside the parentheses removes the ".py"
this.[main-method]()发布于 2016-06-22 22:15:25
import,在任何一个版本中,都只重新加载一次脚本。您正在寻找reload函数:
from importlib import reload
import sys
def main():
pass
def x():
reload(sys.modules[__name__])
main()这段代码将重新加载您当前所在的模块(可能是__main__),并从中重新运行一个方法。如果要从解释器中重新加载脚本,请改为执行以下操作:
>>> from importlib import reload
>>> def x():
... reload(mymodule)
... mymodule.main()
...
>>> import mymodule
>>> mymodule.main()
>>> # Do some stuff with mymodule
>>> x()如果脚本位于一个奇怪的位置,您可能需要用mymodule = importlib.import_module("".join(sys.argv[0].split(".py")))替换import mymodule。
资料来源:
发布于 2016-06-22 22:38:38
我做到了!
def x(): # make what I'm doing now at this very moment easier
main()
print("It works!")
def y(): # calls x() after loading most recent version
import importlib
from imp import reload
this = importlib.import_module("".join(sys.argv[0].split(".py"))) # sys.argv gives [module-name].py and the rest of the code inside the brackets removes the ".py"
this = reload(this)
this.x()https://stackoverflow.com/questions/37970564
复制相似问题