如何“停止”和“恢复”长时间运行Python脚本?
我编写了处理大量大型文本文件的 Python 脚本,并且可能运行很多时间。有时,需要停止正在运行的脚本并稍后恢复。停止脚本的可能原因是程序崩溃、磁盘“空间不足”情况或许多其他必须执行的情况。我想为脚本实现一种“停止/恢复”机制。
- 停止时:脚本退出并退出保存其当前状态。
- 恢复:脚本启动,但从最新保存的状态继续,
我将使用pickle和signal模块来实现它。
我很高兴听到如何以 pythonic 方式做到这一点。
谢谢你!
I wrote Python script that processes big number of large text files and may run a lot of time. Sometimes, there is a need to stop the running script and to resume it later. The possible reasons to stop the script are program crash, disk 'out of space' situation or many others when you have to do it. I want to implement kind of "stop/resume" mechanism for the script.
- On stop: the script quits & saves its current state.
- On resume: the script starts, but continues from the latest saved state
I'm going to implement it using the pickle and the signal modules.
I'll be glad to hear how to do it in pythonic way.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一些简单的事情,希望可以帮助您:
运行示例:
Here is something simple that hopefully can help you:
Example of running:
如果您想读取大文件,只需使用文件句柄,一次读取一行,根据需要处理每一行。如果您想保存 python 会话,那么只需使用 dill.dump_session 即可——它将保存所有现有对象。其他答案将失败,因为
pickle
无法腌制文件句柄。然而,dill 可以序列化几乎所有 Python 对象——包括文件句柄。然后退出 python 会话,然后重新启动。当您
load_session
时,您会加载dump_session
调用时存在的所有对象。就这么简单。
在此处获取
dill
:https://github.com/uqfoundationIf you are looking to read big files, just use a file handle, and read the lines one at a time, processing each line as you need to. If you'd like to save the python session, then just use
dill.dump_session
-- and it will save all existing objects. Other answers will fail aspickle
cannot pickle a file handle.dill
, however, can serialize almost every python object -- including a file handle.Then quit the python session, and restart. When you
load_session
, you load all the objects that existed at the time of thedump_session
call.Simple as that.
Get
dill
here: https://github.com/uqfoundation执行可能让它完全休眠,或者(除了安全性的例外),脚本的状态可以被
pickle
d、压缩和存储。http://docs.python.org/library/pickle.html
http://docs.python.org/library/marshal.html
http://docs.python.org/library/stdtypes.html (5.9)
http://docs.python.org/library/archiving.html
http://www.henrysmac.org/?p=531
The execution could sleep it's life away, or (aside from the exceptions of security), the state of the script can be
pickle
d, zipped, and stored.http://docs.python.org/library/pickle.html
http://docs.python.org/library/marshal.html
http://docs.python.org/library/stdtypes.html (5.9)
http://docs.python.org/library/archiving.html
http://www.henrysmac.org/?p=531