【问题标题】:Iterating through next after a certain amount of time一定时间后迭代next
【发布时间】:2020-04-20 06:32:57
【问题描述】:

假设我有以下代码:

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),可能需要无限时间,我只想尝试(该功能也可能有一些错误)最多1000秒,如果时间超过,我会喜欢停止执行并从另一个 python 文件中执行下一个函数。

有什么想法吗?

【问题讨论】:

标签: python time python-import


【解决方案1】:

你可以试试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?

【讨论】:

    猜你喜欢
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 2018-06-19
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    相关资源
    最近更新 更多