M
M
Millerish2016-06-25 17:28:00
Python
Millerish, 2016-06-25 17:28:00

Python how to limit the execution time of a function?

Good afternoon!
I run into a problem with a function that either freezes or takes too long (sometimes):


response = requests.get(url)
parsed_body = html.fromstring(response.text)
title = parsed_body.xpath('//title/text()')

Maybe it's because of the internet or a website or something else. How can I "tell" pion that a function has a maximum allowed execution time?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Burov, 2016-06-25
@Millerish

Set timeout docs.python-requests.org/en/master/user/quickstart...

K
kapernikxd, 2019-01-24
@kapernikxd

timeout=5 can be added. In this example, 5 sec.
try:
response = requests.get(url, timeout=5)
parsed_body = html.fromstring(response.text)
title = parsed_body.xpath('//title/text()')
except:
print("time out")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question