有没有因为一个愚蠢的错误而在经过10个小时的繁重计算后导致代码崩溃?
plsnocrash的Python项目详细描述
请不要崩溃
设置
此软件包没有依赖项,您可以使用pip:
pip install plsnocrash
让我试试
你有没有过一些计算密集型的代码运行几个小时,却只为了让它崩溃?
最后是因为一些愚蠢的原因?我有,通常是我保存数据的地方
因为我使用了文件路径而不是文件对象,或者混淆了参数的顺序
对于pickle.dump
。
使用@let_me_try
装饰器,而不是让所有数据冒烟。会的
如果标记的代码引发异常,请将您拖到交互式解释程序。会的
还允许您访问违规函数作用域中的变量,以及所有
调用堆栈上每个其他函数作用域中的变量。从那里
不管问题是什么,你都可以修复,然后像什么都没发生一样恢复执行。
下面是一个示例:
root@710027b06106:/plsnocrash/examples# cat let_me_try.py
import plsnocrash
import time
import pickle
def train():
time.sleep(10)
return [1,2,3,4,5]
@plsnocrash.let_me_try
def save(x):
# Oops, that should be a file object, not a string
pickle.dump(x, 'test.pkl')
if __name__ == '__main__':
x = train()
save(x)
print("All done!")
root@710027b06106:/plsnocrash/examples# python let_me_try.py
Caught exception: file must have a 'write' attribute
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/plsnocrash/plsnocrash.py", line 65, in wrapper
return f(*args, **kwargs)
File "let_me_try.py", line 13, in save
pickle.dump(x, 'test.pkl')
TypeError: file must have a 'write' attribute
Call to save(args=([1, 2, 3, 4, 5],), kwargs={}) failed.
Use save(arg1, ...) or resume(arg1, ...) to call the function again with the given arguments and resume execution.
If the function raises another exception, you will end up at another console.
Use skip(return_value) to skip the function call and resume execution as if it had returned 'return_value'.
Global and local variables are available for all scopes on the call stack under the list call_stack.
e.g. call_stack[0]['x'] returns the variable 'x' from save (the failing function),
and call_stack[1]['y'] returns the variable 'y' from the function that called save.
The original positional arguments are available as the tuple 'args',
and keyword arguments are available as the dictionary 'kwargs'.
Use quit() or exit() to give up and stop the whole program.
>>> import pickle
>>> pickle.dump(args[0], open('test.pkl','wb'))
>>> skip()
Call skipped
>>>
Resuming execution
All done!
root@710027b06106:/plsnocrash/examples# ls
test.pkl
重试
还可以使用@retry(limit=n)
decorator,它将重新运行函数,直到函数成功或
重试后放弃。
root@710027b06106:/plsnocrash/examples# cat retry.py
import plsnocrash
fail_counter = 0
@plsnocrash.retry(5)
def get_data():
global fail_counter
# Fail three times before completing
if fail_counter < 3:
fail_counter += 1
raise ValueError("Something went wrong")
return "some data"
if __name__ == '__main__':
print(get_data())
root@710027b06106:/plsnocrash/examples# python retry.py
Caught exception: Something went wrong, retry 1/5
Caught exception: Something went wrong, retry 2/5
Caught exception: Something went wrong, retry 3/5
some data