一定时间后迭代 next

Iterating through next after a certain amount of time

假设我有以下代码:

possibilities = range(20)
input_name = 4
for i in possibilities:
  exec("import Function_" + str(i))
  exec("Function_" + str(i) + ".solveproblem(" + str(input_name) + ")")

自从第二个 exec 函数,例如Function_3.solveproblem(4),可以花费无限多的时间,我只想 try(该函数也可能有一些错误)最多 1,000 秒,如果时间超过,那么我想停止执行并通过另一个 python 文件中的下一个函数。

有什么想法吗?

您可以尝试使用 time

的计时器
base = time.time() # Get time before start
for each in possibilities:
    ''do your stuff''
    if time.time()-base>100:
        break # Time limit

或者如果无法滑入,考虑另起一个帖

def timer:
    base = time.time() # Get time before start
    while True:
        if time.time()-base==100:
            thread.interrupt_main()

            break # Time limit
thread = threading.Thread(target=timer)

thread.start()

'''
now do the rest
'''

How to exit the entire application from a Python thread?