是否可以指定等待代码在Python中运行的最长时间?

Sha*_*kol 6 python timeout

我有一段代码需要从中获取输出:

gps = get_gps_data()
Run Code Online (Sandbox Code Playgroud)

虽然如果花费太长时间才能获得输出get_gps_data(),我想取消该过程并设置gpsNone。修改功能是不可能的,因此有没有办法指定等待某些代码运行并中止的最长时间(如果达到该时间,例如5秒)?

Pra*_*mar 7

您可以执行以下操作。这将适用于您要检查并在一段时间后停止的任何逻辑或功能。您要检查和取消的功能在单独的线程中执行并受到监视。等待3秒钟后,它被取消。

Just put your code inside the test function (you can rename the functions). test function tries to sleep for 100 seconds (could be any logic). But the main call future.result(3), waits only for 3 seconds else TimeoutError is thrown and some other logic follows.

import time
import concurrent.futures as futures


def test():
    print('Sleeping for 100 seconds')
    time.sleep(100)
    # Add your code here
    # gps = get_gps_data()
    return 'Done'


# Main
with futures.ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.submit(test)
    try:
        resp = future.result(3)
    except futures.TimeoutError:
        print('Some other resp')
    else:
        print(resp)
    executor._threads.clear()
    futures.thread._threads_queues.clear()
Run Code Online (Sandbox Code Playgroud)

You can try to minimise the wait time inside the test function to some value less than 3 seconds. In this case, the original result returned from test function will be used.