如何使用超时装饰器模块?

时间:2019-06-25 19:37:53

标签: python-3.x multithreading pypdf2

我需要做的就是在功能开启时间过长时停止该功能。我想使用超时装饰器来做到这一点。但是,这样做时会出现一些错误。

我尝试了其他方法,例如使用Pebble或自己的多线程,但是几乎总是得到相同的基本错误消息。

此处的代码是从timeout_decorator文档中复制并粘贴的,除了将'use_signals'设置为false之外,因为我不在UNIX上:

import time
import timeout_decorator

@timeout_decorator.timeout(5, use_signals=False)
def mytest():
    print("Start")
    for i in range(1,10):
        time.sleep(1)
        print("{} seconds have passed".format(i))

if __name__ == '__main__':
    mytest()

以下错误:

Traceback (most recent call last):
  File "C:\T3AJM\test3.py", line 12, in <module>
    mytest()
  File "C:\Users\amcgrail\AppData\Local\Programs\Python\Python37\lib\site-packages\timeout_decorator\timeout_decorator.py", line 91, in new_function
    return timeout_wrapper(*args, **kwargs)
  File "C:\Users\amcgrail\AppData\Local\Programs\Python\Python37\lib\site-packages\timeout_decorator\timeout_decorator.py", line 146, in __call__
    self.__process.start()
  File "C:\Users\amcgrail\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 112, in start
    self._popen = self._Popen(self)
  File "C:\Users\amcgrail\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\amcgrail\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Users\amcgrail\AppData\Local\Programs\Python\Python37\lib\multiprocessing\popen_spawn_win32.py", line 89, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Users\amcgrail\AppData\Local\Programs\Python\Python37\lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
_pickle.PicklingError: Can't pickle <function mytest at 0x00000000022CF1E0>: it's not the same object as __main__.mytest
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\amcgrail\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 99, in spawn_main
    new_handle = reduction.steal_handle(parent_pid, pipe_handle)
  File "C:\Users\amcgrail\AppData\Local\Programs\Python\Python37\lib\multiprocessing\reduction.py", line 87, in steal_handle
    _winapi.DUPLICATE_SAME_ACCESS | _winapi.DUPLICATE_CLOSE_SOURCE)
PermissionError: [WinError 5] Access is denied
[Finished in 0.244s]

我也尝试过使用命令行作为管理员,以及使用Atom作为管理员,但均无济于事。

我似乎也无法通过try / except块来捕获它,尽管我认为这样做没有帮助。

是否处于if __name__...条件似乎无关紧要。

重新启动计算机没有任何作用。

多处理模块适用于给定的测试代码,但是我不确定如何将其用于停止功能。

感谢您的帮助。

0 个答案:

没有答案