try except inside try except [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Is the usage of try...except below correct? If not, what do I have to change?
try:
name_file = input('Welcome user, enter the name of the file to be opened: ')
file = open('../' + name_file, 'r')
# print(file.readlines(), end=' ')
except FileNotFoundError as err:
print('File not found :(')
else:
try:
res = int(input('Which representation do you want to use? [1] Adjacency List - [2] Adjacency matrix'))
except ValueError as err:
print('Invalid option')

This is correct syntax for try-except-else and will execute as needed if a user enters a non-int value for the second prompt. However, if a different number is entered, the ValueError will not be thrown.
try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
finally:
# Some code .....(always executed)
https://www.geeksforgeeks.org/python-try-except/#:~:text=Else%20Clause%20In%20python%2C%20you%20can%20also%20use,the%20try%20clause%20does%20not%20raise%20an%20exception.

Related

There is a faster way to use googlemaps API in Python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
Im currently using python to georefernce a dataset of 10512 observations, but is way slow using this code
gmaps = googlemaps.Client(key='APIKEYXXXXXXXXXXXXXXXXXXXXXX')
BD2021['lat']=0
BD2021['lon']=0
for i in range(len(BD2021)):
try:
geocode_result = gmaps.geocode(BD2021['DIRECCION'][i]+',Barranquilla, Colombia')
BD2021['lat'][i]=geocode_result[0]['geometry']['location']['lat']
BD2021['lon'][i]=geocode_result[0]['geometry']['location']['lng']
except:
try:
geocode_result = gmaps.geocode(BD2021['RAZON_SOCIAL'][i]+',Barranquilla, Colombia')
BD2021['lat'][i]=geocode_result[0]['geometry']['location']['lat']
BD2021['lon'][i]=geocode_result[0]['geometry']['location']['lng']
except:
pass
Theres is any faster way that you can recommend, that script have been loading for 30 mins and I dont know even its doing a good job.
Without knowing at all what BD2021 is in more detail, it's hard to definitively help, but a variation like this has more robust error handling, and also a cache, so if the same address happens to be multiple times in your dataset, the program will only geocode it once per run. (You could use a package like diskcache for a more persistent cache.)
from functools import cache
# ...
gmaps = googlemaps.Client(key="APIKEYXXXXXXXXXXXXXXXXXXXXXX")
#cache
def get_geocode(address):
return gmaps.geocode(address)
BD2021["lat"] = {}
BD2021["lon"] = {}
for i in range(len(BD2021)):
for possible_address in (
BD2021["DIRECCION"][i] + ",Barranquilla, Colombia",
BD2021["RAZON_SOCIAL"][i] + ",Barranquilla, Colombia",
):
try:
geocode = get_geocode(possible_address)
if geocode and geocode[0]:
BD2021["lat"][i] = geocode[0]["geometry"]["location"]["lat"]
BD2021["lon"][i] = geocode[0]["geometry"]["location"]["lng"]
break
except Exception as e:
print(f"Error processing {possible_address}: {e}")
else:
print(f"Could not find geocode for index {i}")

Not instantly getting out a loop with break [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
When I run this easy program and want to exit it, I need to type exit 2 times (at line 7).
def registration():
def username_registration():
entering_username = True
while entering_username:
print("Type exit to leave the registration.")
usernam_from_registration = input("Enter username: ")
if usernam_from_registration == "exit":
break
lenght_usernam_from_registration = len(usernam_from_registration)
if lenght_usernam_from_registration > 15:
print("too long")
else:
return usernam_from_registration
username_registration()
print(username_registration())
registration()
Why is this and how can I make it so I only need to write it one time?
This is because you are calling the username_registration() function twice.
username_registration()
print(username_registration())
The first time you call it, nothing happens because you are not doing anything with the result.

While loop and For loop together [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Hi I want to run make for loop to run infinitely.
for eg.
while True:
try:
script()
except Exception as e:
script()
continue
as below because in For loop I have lists where i want to apply on scripts which run in sequencing and continuous
while True:
try:
for symbol in symbol:
script()
except Exception as e:
for symbol in symbol:
script()
continue
I guess you are trying to run a program even when there is an exception and break at some condition, you do not want to run the loop infinitely I suppose. you can do
While true:
try:
for symbol in symbols:
script(symbol) ' you should break however somewhere
Exception as e:
continue

Close Only One Chrome Tab on TaskBar [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have 2 chrome tabs like that:
Tabs
I want to close one of them.I will use python to close.How can I close?
Using psutil module this can be achieved
Given code will kill first instance of process found. (If you want to kill all instance you can remove/comment return statement inside try block)
import psutil
def kill_process_by_name(processName):
# Iterate over all running processes
for proc in psutil.process_iter():
# Get process detail as dictionary
pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time'])
# Check if process name contains the given name string.
try:
if processName.lower() in pinfo['name'].lower():
print(pinfo)
p = psutil.Process(pinfo['pid'])
p.terminate()
return
except Exception as e:
pass
#ignore any exception
return
kill_process_by_name( processName='chrome')

Python - Undo script if script fails [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Sometimes when I run a function in my python script and if the function gives me an output which is not desired, I need to undo this step and then try running the function again with different parameters. Is there a way that I can have the script undo what it has done if my function gives me a wrong output.For only one set of parameters, the desired output is acheived.
PS: By running the function means making permanent changes.
Example:
def function():
for i in range(parameters):
value = perform_operation(parameters[i]) #makes permanent changes
if value != some_value:
undo(perform_operation())
You need to create another function than cleans what was done in the main function for example (delete newly created files, remove installed packages, etc ...) and use it.
def main_func():
proc = subprocess.Popen('touch test test2')
return proc.returncode
def clean_main_func():
subprocess.Popen('rm test test2')
def __name__ == '__main__':
result = main_func()
if main_func() != 0 :
clean_main_func()
or you can raise an error then catch it:
def main_func():
proc = subprocess.Popen('touch test test2')
if proc.returncode !=0 :
raise Error
def clean_main_func():
subprocess.Popen('rm test test2')
def __name__ == '__main__':
try:
result = main_func()
except Error:
clean_main_func()
It's juste an example , and hope it answer your question.

Categories