安静地重新启动Python解释器 [英] Restarting a Python Interpreter Quietly

查看:298
本文介绍了安静地重新启动Python解释器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序内部嵌入了python解释器.该应用程序需要很长时间才能启动,并且我无法在不重新启动整个应用程序的情况下重新启动解释器.我想做的基本上是保存解释器的状态并轻松地返回该状态.

I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter and return to that state easily.

我首先将所有模块的名称存储在python解释器开始的sys.modules中,然后在请求时从sys.modules中删除所有新模块.这似乎使解释器准备重新导入相同的模块,即使它之前已经导入了它们也是如此.但是,这似乎并非在所有情况下都有效,例如使用单例类和静态方法等.

I started by storing the names of all modules in sys.modules that the python interpreter started with and then deleting all new modules from sys.modules when requested. This appears to make the interpreter prepared to re-import the same modules even though it has already imported them before. However, this doesn't seem to work in all situations, such as using singleton classes and static methods, etc.

如果可以避免的话,我宁愿不要在该解释器中嵌入另一个解释器,因为这样会失去使用应用程序API的便利性(以及我想像的轻微的速度损失).

I'd rather not embed another interpreter inside this interpreter if it can be avoided, as the ease of being able to use the applications API will be lost (as well as including a slight speed hit I imagine).

那么,有人知道我可以存储解释器的状态然后返回到此状态以便它可以应对所有情况的方法吗?

So, does anyone know of a way I could store the interpreter's state and then return to this so that it can cope with all situations?

谢谢

推荐答案

从ActiveState食谱尝试以下代码: http://code.activestate.com/recipes/572213/

Try this code from ActiveState recipes: http://code.activestate.com/recipes/572213/

它扩展了pickle,因此它支持对shell控制台中定义的任何东西进行酸洗.理论上,根据他们的文档,您应该只可以腌制 main 模块:

It extends pickle so it supports pickling anything defined in the shell console. Theoretically you should just be able to pickle the main module, according to their documentation:

import savestate, pickle, __main__
pickle.dump(__main__, open('savestate.pickle', 'wb'), 2)

这篇关于安静地重新启动Python解释器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆