How can I return to my loop after an exception?

I have the code below:

import urllib.request
import json

flag_servidor = 0
flag_salva_txt = 0
numero = 0

#codigo para verificar se há conexao como servidor e caso nao
#haja ele criar um arquivo txt com as infos

while 1:
    try:
        url = urllib.request.urlopen('http://IP/CAMINHO/get_infos.php')
        x_ = url.read()
        y_ = json.loads(x_.decode('utf-8'))
        get_turno_ = y_["turno"]
        print(get_turno_)

        #salva as infos do txt dentro do banco de dados
        if flag_salva_txt == 1: #significa que temos infos para serem salvas
            arquivo = open('novo-arquivo1.txt', 'r')
            for linha in arquivo:
                linha = linha.rstrip()
                valor = linha.split(";")
                print(valor[0])
            flag_salva_txt = 0
        continue
    except Exception as e:
        print("Servidor indisponível.Erro:", e)
        if flag_salva_txt == 0:
            #após salvar txt 
            flag_salva_txt = 1
            numero = numero +1
            arquivo = open('novo-arquivo'+str(numero)+'.txt', 'w')
            arquivo.write('nova linha;123;1pop' + '\n')
            arquivo.close()
        continue

The problem is that: when an exception happened for the first time it shows me message error but when it happens for second time my code stop running and doesn´t show anything.

Upvotes: 0

Views: 43

Answers (1)

AKX
AKX

Reputation: 169051

I'm still not quite crystal clear about what your program is supposed to do, but maybe something like this helps.

I refactored your program to a separate function to get the data, and printing it out (or whatever you like to do) is in the main loop.

In addition, to not hit the server as fast as your script can, there's a delay of 5 seconds between every request, successful or not.

import datetime
import time
import urllib.request
import json


def get_turno():
    url = urllib.request.urlopen("http://IP/CAMINHO/get_infos.php")
    data = json.loads(url.read().decode("utf-8"))
    return data["turno"]


while True:
    try:
        turno = get_turno()
    except Exception as exc:
        print("Retrieving turno data failed: {}".format(exc))
    else:
        current_time = datetime.datetime.now().isoformat()
        print("Time: {} - Turno: {}".format(current_time, turno))
    time.sleep(5)

Upvotes: 1

Related Questions