Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to write a polling function in python

I wrote a polling function to check the value of reg_result variable for 120 seconds.

reg_result = 0
while_timeout = time.time() + 120
while reg_result is not "REGISTERED" and time.time() < while_timeout:
    reg_result = LeshanObj.validate_reg_time(parameter_1)

Is there any other better way of writing a polling method?

Is it possible by not using a while loop?

like image 353
RejeeshChandran Avatar asked Jan 18 '17 07:01

RejeeshChandran


People also ask

How do you create a poll in Python?

A call to method poll(timeout) will return a list of tuples where each tuple is comprised of a file descriptor and the event. If no event occurred within the time as specified by timeout, an empty list will be returned.

What does poll return in Python?

poll always returns immediately. It effectively does a wait with a timeout of 0, catches any exception, and returns None if the process hasn't completed.

What is polling in programming?

Polling, or polled operation, in computer science, refers to actively sampling the status of an external device by a client program as a synchronous activity. Polling is most often used in terms of input/output (I/O), and is also referred to as polled I/O or software-driven I/O.


1 Answers

There is a library in python Polling(https://pypi.python.org/pypi/polling/0.3.0) You can use this

from polling import TimeoutException, poll
try:
    poll(lambda: reg_result=='REGISTERED', timeout=120, step=1)
except TimeOutException as tee:
    print "Value was not registered"

Hope it helps.

like image 55
Sandeep Hukku Avatar answered Oct 24 '22 11:10

Sandeep Hukku