0

我在一行中有一个命令(Fit.perform()from import xspec,但没关系,因为这个问题很笼统,也可以应用于其他 python 命令)需要一段时间才能完成。

我只是想知道命令运行时的执行时间,所以当它还没有完成执行时。如果我想在命令执行期间停止命令,这是必要的,例如因为它需要太多时间才能结束。

所以,我需要这样的东西:

if **you_are_taking_so_much_time**:
    do_something_else

不可能使用类似timeor的方法,timeit因为它们仅在命令执行结束时计算时间,而不是在命令运行时计算时间。

可能吗?

我在 MacOS 上使用 python 2.7。

4

2 回答 2

1

您将不得不使用监视器线程:

import threading
import time

done = False

def longfun():
    global done
    print("This will take some time.")
    time.sleep(60)
    done = True

def monitor():
    global done
    timeout = 10
    print("Wait until timeout.")
    while not done and timeout > 0:
        time.sleep(1)
        timeout -= 1

lt = threading.Thread(target=longfun)
lt.start()
mt = threading.Thread(target=monitor)
mt.start()

mt.join()
if done == False:
    print("Long thread not done yet. Do something else.")

lt.join()

请注意,这确实会等到“长”线程完成。您没有提到要停止长时间运行的操作。如果这样做,则必须在线程中正确实现它,包括启动/停止/进度功能(通常这与使用bit 来查看是否应该继续的while循环一起使用。running

于 2018-01-11T08:08:38.250 回答
0

像这样:

import time,thread
def test_me(hargs):
    func,args,timeout = hargs
    start_time = time.time()
    thread.start_newthread(func,args)
    while True :
        if My_expected_value:#where store this ?
            print "well done !"
            break
        elif time.time() > (timeout + start_time) :
            print "oh! to late, sorry !"
            break
        time.sleep(timeout/100)
thread.start_newthread(test_me,((func,args,timeout),))

重要警告:非冻结应用程序需要使用线程,为此获得 3 个线程:1-main app、2-test_me、3- Your function(func)

不要忘记向您的函数添加外部变量(用于杀死您的函数线程)

于 2018-01-11T08:08:35.970 回答