Re-running a python code with a while loop - python

How could I write a piece of code that recognizes if the any type of error has occurred and if it does the code just runs on a loop. What would be a function that I would place in <some error occurs> so it recognizes any error 0utput and re runs the code within 10 seconds.
while True:
<all your code>
if <some error occurs>:
time.sleep(10)
continue

Simply use try...except
while True:
try:
<all_your_code>
except:
time.sleep(10)
continue
Read this for better understanding: https://www.programiz.com/python-programming/exception-handling

Related

Unexpected EOF while parsing Syntax Error in Python

I just started using Python's keyboard module. I was exploring with the code below until there was a error occurring at the end on line 5. The goal of the code below is to detect if I pressed the "a" on my keyboard. I attempted to put a semicolon at the end of the print function, and I tried to replace the print("A") with pass and break but Python gave me the same error as before.
import keyboard
while True:
try:
if keyboard.is_pressed('a'):
print("A")
Output:
File "c:\users\emma\mu_code\keyboard.py", line 6
Syntax Error: unexpected EOF while parsing
Why do I have this syntax error and how can I get rid of it?
In your code add the except block, like so:
import keyboard
while True:
try:
if keyboard.is_pressed('a'):
print("A")
except:
#do something else, if there is an error, or any other key is pressed
If u dont know if u need try except, then just dont keep it in the try block:
import keyboard
while True:
if keyboard.is_pressed('a'):
print("A")
You didn't add except part.
If you are using try/except statement you need an except statement.
Make it.
import keyboard
while True:
try:
if keyboard.is_pressed('a'):
print("A")
else:
# Rest code . If you don't want to do anything then simply pass
pass

SyntaxError: invalid syntax (try)

I'm writing a script to start all of my services like Admin and Managed Server using Python. When i tried executing it says "SyntaxError: Invalid Syntax(try). Please find the code below
import time
sleep=time.sleep
configFile =
"/u02/weblogic/user_projects/domains/base_domain/userConfig.dat"
pwFile = "/u02/weblogic/user_projects/domains/base_domain/userKey.dat"
while True:
try:
connect(userConfigFile=configFile,
userKeyFile=pwFile,
url='t3://my.Adminserver.com:7001')
break
except:
sleep(60)
nmConnect(userConfigFile=configFile,
userKeyFile=pwFile,
domainName='base_domain')
nmStart('ManageServer1')
exit()
The try/except block should have 4 spaces. Functions, classes, if statements, while loops, for loops and try/except block all get 4 spaces.
try:
connect(userConfigFile=configFile,userKeyFile=pwFile,url='t3://localhost:7001')
break
except:
The rest of your code which you posted has a few other things perhaps I would change.I wouldn't set up a sleep variable like that I personally would just call time.sleep(). Also don't forget while loops gets 4 spaces of indentation and so try/except blocks. I'm also not sure about the last 5 lines of code if they are part of the except clause but if they are space them in 8 times (the reason is because we need to get past the while loop + put the code in the except clause so 8 spaces). I would edit your code snippet in your question with the correct indentation and perhaps comment out what it is suppose to do and such.
import time
configFile = "/u02/weblogic/user_projects/domains/base_domain/userConfig.dat"
pwFile = "/u02/weblogic/user_projects/domains/base_domain/userKey.dat"
while True:
try:
connect(userConfigFile=configFile,
userKeyFile=pwFile,
url='t3://my.Adminserver.com:7001')
break
except:
sleep(60)
nmConnect(userConfigFile=configFile,
userKeyFile=pwFile,
domainName='base_domain')
nmStart('ManageServer1')
exit()
A SyntaxError is at, or before, the ^ symbol. So the error is going to be before the try: itself -- maybe a missing parenthesis on a previous line, maybe try is not indented correctly -- we cannot tell because you have elided all the previous code, but that's where you should look.

Python how to rerun code after it stops

i am newbie to Programming,i am running this python code in my computer Normally it runs correctly, but sometimes the code stops due to network conditions. once it stopped i have to run the code manually. Does anyone know how to modify this code to retry if the code fails to run
This is the code
for line in f:
api.update_status(line)
time.sleep(1200)
The code in Noel's answer makes it more likely that the program doesn't stop until the loop goes through every item in f.
The problem though is that an exception could occur in the line after except and the program would stop again.
try this:
i = 0
while i < len(f):
try:
api.update_status(f[i])
i += 1
except:
pass
This way, i only gets incremented if api.update is successful so no items will be skipped and the program wont stop until all f are updated

How to stop code execution of for loop from try/except in a Pythonic way?

I've got some Python code as follows:
for emailCredentials in emailCredentialsList:
try:
if not emailCredentials.valid:
emailCredentials.refresh()
except EmailCredentialRefreshError as e:
emailCredentials.active = False
emailCredentials.save()
# HERE I WANT TO STOP THIS ITERATION OF THE FOR LOOP
# SO THAT THE CODE BELOW THIS DOESN'T RUN ANYMORE. BUT HOW?
# a lot more code here that scrapes the email box for interesting information
And as I already commented in the code, if the EmailCredentialRefreshError is thrown I want this iteration of the for loop to stop and move to the next item in the emailCredentialsList. I can't use a break because that would stop the whole loop and it wouldn't cover the other items in the loop. I can of course wrap all the code in the try/except, but I would like to keep them close together so that the code remains readable.
What is the most Pythonic way of solving this?
Try using the continue statement. This continues to the next iteration of the loop.
for emailCredentials in emailCredentialsList:
try:
if not emailCredentials.valid:
emailCredentials.refresh()
except EmailCredentialRefreshError as e:
emailCredentials.active = False
emailCredentials.save()
continue
<more code>

why do we use 'pass' in error handling of python?

It is conventional to use pass statement in python like the following piece of code.
try:
os.makedirs(dir)
except OSError:
pass
So, 'pass' bascially does not do anything here. In this case, why would we still put a few codes like this in the program? I am confused. Many thanks for your time and attention.
It's for the parser. If you wrote this:
try:
# Code
except Error:
And then put nothing in the except spot, the parser would signal an error because it would incorrectly identify the next indentation level. Imagine this code:
def f(x):
try:
# Something
except Error:
def g(x):
# More code
The parser was expecting a statement with a greater indentation than the except statement but got a new top-level definition. pass is simply filler to satisfy the parser.
This is in case you want the code to continue right after the lines in the try block. If you won't catch it - it either skips execution until it is caught elsewhere - or fails the program altogether.
Suppose you're creating a program that attempts to print to a printer, but also prints to the standard output - you may not want it to file if the printer is not available:
try:
print_to_printer('hello world')
except NoPrinterError:
pass # no printer - that's fine
print("hello world")
If you would not use a try-catch an error would stop execution until the exception is caught (or would fail the program) and nothing would be printed to standard output.
The pass is used to tell the program what to do when it catches an error. In this particular case you're pretty much ignoring it. So you're running your script and if you experience an error keep going without worrying as to why and how.
That particular case is when you are definite on what is expected. There are other cases where you can break and end the program, or even assign the error to a variable so you can debug your program by using except Error as e.
try:
os.makedirs(dir)
except OSError:
break
or:
try:
os.makedirs(dir)
except OSError as e:
print(str(e))
try:
# Do something
except:
# again some code
# few more code
There are two uses of pass. First, and most important use :- if exception arises for the code under try, the execution will jump to except block. And if you have nothing inside the except block, it will throw IndentationError at the first place. So, to avoid this error, even if you have nothing to do when exception arises, you need to put pass inside except block.
The second use, if you have some more code pieces after the try-except block (e.g. again some code and few more code), and you don't put pass inside except, then that code piece will not be executed (actually the whole code will not be executed since compiler will throw IndentationError). So, in order to gracefully handle the scenario and tell the interpreter to execute the lines after except block, we need to put pass inside the except block, even though we don't want to do anything in case of exception.
So, here pass as indicated from name, handles the except block and then transfers the execution to the next lines below the except block.

Categories