在使用带有try&except子句的 @fork 装饰器时,我遇到了问题。在SageMathCell上,这段代码运行良好,而在Jupyter和CoCalc上,它均未正确引发异常子句。在CoCalc上,它起初根本不认识 @fork 装饰器,但是from sage.all import *
(问题的思想:@fork decorator not recognized in script
)似乎有所帮助。
代码段:
from sage.all import * #for CoCalc
a_0,a_1 = var('a_0,a_1');s = [a_0,a_1]
equations = [69*a_0 + 4556 == 69*a_0 + 63*a_1, 69*a_1 - 3350 == -67*a_0 + 57*a_1, 63*a_0 - 3876 == -1542, 63*a_1 + 2850 == 7406]
try:
@fork(timeout=0.1, verbose=True) #use e.g. 0.1 and 10
def DirectSolution():
sage_solution = solve(equations, s , solution_dict=True)
print('Solves in time ,','sage_solution:',sage_solution)
return sage_solution
sage_solution = DirectSolution()[0]
except KeyboardInterrupt:
sage_solution = []
print('Takes too long , ','sage_solution:',sage_solution)
print('Execute the rest of the code, ','sage_solution:',sage_solution)
在没有try / except的情况下在@fork装饰器上运行0.1秒钟,我得到了KeyboardInterrupt
错误,这就是为什么我在except子句中使用它。通常不应该在用户按下中断键时引发此异常吗?
如上所述,在SageMathCell上 该代码按预期工作:code on SageMathCell
用10秒计算
解决方案并打印出文本。对于
设定0.1秒
sage_solution = []
并打印出来
文字。
但是,在Jupyter和CoCalc上,它都没有在0.1秒内正确使用异常。 我收到以下消息:
Killing subprocess 1346 with input ((), {}) which took too long
Execute the rest of the code, sage_solution: N
意味着它没有执行except子句:
sage_solution = []
print('Takes too long , ','sage_solution:',sage_solution)
我不确定要在这里查找什么,因为它正在一个平台上运行。一个简单的try / except示例工作正常(1st example)。另一个想法是KeyboardInterrupt
可能是问题,但删除它并没有任何改变。
我是Sage / Python的新手,所以可能有一个简单的解决方案,但我很乐意提供任何帮助。