Loop to run 4 times to try run a SQL procedure, after 4 attempts then stop

2024/11/19 15:31:40

I have attempted to write some code in python to do a loop 4 times. It will fail as spTest doesn't exist. So I want to try loop again (repeated 4 times total) if it still can't find it, I want to break out and raise an error.

import traceback
import urllib
from datetime import datetime
import numpy as np
import pandas as pd
import sqlalchemy as db
from sqlalchemy import event
import logging
from tqdm import tqdm
import smtplib
import ssl
from time import sleepdef test():for x in range(0, 4):  # try 4 timestry:df = pd.read_sql(sql='EXEC [prod].[spTest]', con=engine, )str_error = Noneexcept Exception as str_error:print(str_error)passif str_error:sleep(2)  # wait for 2 seconds before trying to fetch the data againelse:breakprint(df)

Error I get:

if str_error: UnboundLocalError: local variable 'str_error' referenced before assignment

Updated code:

def test():str_error = Nonefor x in range(0, 4):  # try 4 timestry:df = pd.read_sql(sql='EXEC [prod].[spTest]', con=engine, )except Exception as str_error:print(str_error)if str_error:sleep(2)else:breakprint(df)

Issue: No longer loops 4 times.

Answer

Why do you need a separate condition to check if the error occurred? That's exactly what the try/except is for:

for x in range(4):  # try 4 timestry:df = pd.read_sql(sql='EXEC [prod].[spTest]', con=engine, )breakexcept Exception as str_error:print(str_error)sleep(2)  # wait for 2 seconds before trying to fetch the data again
https://en.xdnf.cn/q/118525.html

Related Q&A

Loops in Python 3.4.3

I apologize ahead of time for my ignorance but I have trying to code something in python that requires a question to be asked to the user and the user responds. Dependent on that response, the program …

Adding userdata on create VM operation with Python SDK for Azure

I am using Python sdk for azure creation virtual machine operation. I want some script to be executed whenever the VM starts. So, I have tried adding the custom-data while creating VM with Python. My d…

python obtain the self variable in another class which already has a self function

I want to use the self variables in one class and use them in another class which already has its own self variables how to do I do this. Some code here to help.class A():self.health = 5 class B(): # T…

Cannot pip install package in virtualenv on EC2

Im seeing this weird issue on ec2. Im trying to install lsm-db package inside my virtualenv, it says its successfully installed but when trying to import the package or do pip list its not there.I crea…

Python: string to integer as a key

Im trying to convert a string column in a dataframe to int. The strings should be replaced with an integer as a key value.Data:user_id site_id 100 url1.com 100 url2.com 100 url1.com 101…

Data manipulation, kind of downsampling

I have a large csv file, example of the data below. I will use an example of eight teams to illustrate.home_team away_team home_score away_score year belgium france 2…

Chrome Native Messaging throwing error when sending a base64 string to client

Using Chrome Native Messaging sample app as a template am able make a system call to bashos.system("<bash command>")The requirement is to return a base64 string from the python scriptos…

Exporting DataFrame to Excel using pandas without subscribe

How can I export DataFrame to excel without subscribe? For exemple: Im doing webscraping and there is a table with pagination, so I take the page 1 save it in DataFrame, export to excel e do it again …

Fraction of a real number in python giving complicated answer

Importing Fraction from fractions to give a fractional representation of a real number, but giving responses quite complicated which seems very simple by the paper-pen method. Fractions(.2) giving answ…

Scrape latitude and longitude (Google Maps) inside Script type=text/javascript

Im beginner in Web Scrapping. Im trying to get latitude and longitude from this web: https://urbania.pe/inmueble/proyecto/ememhvin-proyecto-mariscal-castilla-lima-santiago-de-surco-tale-inmobiliaria-65…