Форум сайта python.su
Привет всем. Столкнулся с проблемой долгой загрузки сайта, с помощью requests.get().text
Суть вопроса, как прервать выполнение функции через како либо время?
Решение типа requests.get('link', timeout.text не помогает, функция все так же пытается получить код страницы.
Как можно решить данную проблему?
Офлайн
timeout “не работает” потому что:
NoteОС какая ?
timeout is not a time limit on the entire response download; rather, an exception is raised if the server has not issued a response for timeout seconds (more precisely, if no bytes have been received on the underlying socket for timeout seconds). If no timeout is specified explicitly, requests do not time out.
Офлайн
Вообще достаточно легко гуглится
Офлайн
JOHN_16Ос Linux, дебиан
timeout “не работает” потому что:
Офлайн
Mr.Anderson
Это хорошо - посмотрите варианты по ссылке выше, там , на вскидку, не один вариант который вам подойдет
Офлайн
Взял от туда первое решение
import signal # Register an handler for the timeout def handler(signum, frame): print("Forever is over!") raise Exception("end of time") # This function *may* run for an indetermined time... def loop_forever(): html_codes = requests.get('https://books.google.ru/books?isbn=3659226408').text # Register the signal function handler signal.signal(signal.SIGALRM, handler) # Define a timeout for your function signal.alarm(3) try: loop_forever() except Exception: print('!')
Офлайн
Вопрос закрыт, помогло это решение
import multiprocessing.pool import functools def timeout(max_timeout): """Timeout decorator, parameter in seconds.""" def timeout_decorator(item): """Wrap the original function.""" @functools.wraps(item) def func_wrapper(*args, **kwargs): """Closure for function.""" pool = multiprocessing.pool.ThreadPool(processes=1) async_result = pool.apply_async(item, args, kwargs) # raises a TimeoutError if execution exceeds max_timeout return async_result.get(max_timeout) return func_wrapper return timeout_decorator
Офлайн