0

I have a function which sends a request to a server. But sometimes the server doesn't reply and my code doesn't seem to continue. Now I wanted to implement, that the code continues to run, if no reply is received after a given amount of time. Below the code:


for attempt in range (3):
    try:
        print('Attempt: ' + str(attempt+1))
        print('DUT: ' + str(x))
        time.sleep(1)
        response = request("http://" + ipEntry.get() + port, "temperature_test", x)
        time.sleep(1)
        print(response.text)
        print(response.data.result)
        answer = response.data.result
        logFile.write(time.strftime("%Y_%m_%d-%H_%M_%S\t\t") + str(x) + "\t\t" + str(answer) + "\t\t" + str(readVoltage()) + "\t\t" + str(readCurrent()) + "\n")               
    
    except:
        print('An error occured!')
    else:
        if (response.data.result==False):
            print("Attempt " + str(attempt + 1) + " failed!")
        else:
            break
else:
                print('All 3 attempts failed')

Is it possible to start a counter after the beginning of this function and check with an "if" statement if it has elapsed?

Thanks for any hints and best regards!

pfra
  • 5
  • 1
  • 5
  • i think what you're trying to find is the `continue` [keyword](https://www.w3schools.com/python/ref_keyword_continue.asp#:~:text=The%20continue%20keyword%20is%20used,continues%20to%20the%20next%20iteration.) you can search about that – Ice Bear Oct 09 '20 at 08:07
  • By any chance you are using request library because it has a parameter for that https://requests.readthedocs.io/en/master/user/quickstart/#timeouts – Andi Domi Oct 09 '20 at 08:08
  • I don't know which module/library you are using for the request, but there is probably a `timeout` parameter. – Wups Oct 09 '20 at 08:09
  • Hi all, thanks for the comments! I am using: "from jsonrpcclient import requests". – pfra Oct 09 '20 at 08:12
  • I checked the documentation ( https://jsonrpcclient.readthedocs.io/en/latest/api.html ) but couldn't find a timeout feature... – pfra Oct 09 '20 at 08:31
  • @Philipp i think there is a mention in their [github repository](https://github.com/bcb/jsonrpcclient/issues/129) about something similar. Another approach would be to have a look at [signals with an example described here](https://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python) – Andi Domi Oct 09 '20 at 10:59

0 Answers0