How to stop running Python code for time?

Asked

Viewed 56 times

2

How can I make a chunk of code run for x seconds and then stop? In the specific case, I’m expecting a response from a page using request, but if it takes longer than 5 seconds, I want to stop and make the next request.

1 answer

4

By default, request shall wait indefinitely for a response to a request. If you want to specify a timeout for request, use the parameter timeout

The example below the request timeout will be reached after 10 seconds:

requests.get(`/users/137387/augusto-vasques`, timeout=10)

You can also pass a tuple as a timeout value:

requests.get(`/users/137387/augusto-vasques`, timeout=(10, 5))

The first element of the tuple defines the time limit that must be waited to make a connection and the second element is the time limit that must be waited to read the data after connected.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.