Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何调用一个方法并确保它的执行不会';不要超过一定的时间?_Python_Python 3.x - Fatal编程技术网

Python 如何调用一个方法并确保它的执行不会';不要超过一定的时间?

Python 如何调用一个方法并确保它的执行不会';不要超过一定的时间?,python,python-3.x,Python,Python 3.x,假设我有一个来自第三方库的方法,我无法访问该方法,或者我不想更改其源代码。我希望能够调用该方法,如果它在一段时间内没有返回结果,则我希望取消其执行或继续: # start a timer or something # call that method third_party_method() # if the time has elapsed, say, 1 minute has passed with no result # then cancel it (preferably) #

假设我有一个来自第三方库的方法,我无法访问该方法,或者我不想更改其源代码。我希望能够调用该方法,如果它在一段时间内没有返回结果,则我希望取消其执行或继续:

# start a timer or something


# call that method
third_party_method()

# if the time has elapsed, say, 1 minute has passed with no result

# then cancel it (preferably)
#  and print("too late")

# otherwise print("on time")

我该怎么做?是否有一种简单或标准的方法?

如果花费的时间太长,以下方法不会终止工作,但至少会让您知道:

def f():
    # sleep for 10 seconds
    import time
    time.sleep(10)

def do_we_give_up():
    from concurrent import futures
    executor = futures.ThreadPoolExecutor(max_workers=1)
    future = executor.submit(f)

    # give it a second
    try: 
        for x in futures.as_completed([future], 1):
           # the result
           print(x.result())
    except futures.TimeoutError:
        # no result
        print("timed out")
然后


你不能。。。不完全一样,但是您可以创建一个新的线程/进程来调用该方法,并在一段时间不活动后将其杀死…@Selcuk:cannotkill threads。但是是的,使用
多处理。处理
是唯一可靠的方法之一@托马斯索德扎维茨尼,谢谢。
>>> do_we_give_up()
timed out