Python how to rerun code after it stops - python

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

Related

"undo" goes to int() what shouldn't have happened

I have one problem. While drawing some sprites, why do I have a string named "undo" that goes to int()? (base 10)
import win32gui as w
import os as r
import time as t
import keyboard as kb
import random as ra
fw = w.GetForegroundWindow()
con = w.GetDC(fw)
r.system(f'mode con:cols={64} lines={32}')
r.system('color 07')
def CreateImag(readedlines,x,y):
for u in readedlines:
gg=u.split()
w.BitBlt(con,int(gg[0])+x,int(gg[1])+y,int(gg[2]),int(gg[3]),con,0,0,-1)
print('sprite draw')
t.sleep(2)
rl = []
r.system('cls')
while True:
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"+'='*64+"\n [from x from y f.x+x", end='')
print("f.y+y], for exit type \"exit\", for undo type \"undo\"")
if ag=='undo':
print(list.pop(-1))
break
ag = input('>>')
if ag=='exit':
file = open(f'image{ra.randint(0,100001)}.imag')
for aa in rl:
file.write(f'{aa}\n')
file.close()
rl.append(ag)
CreateImag(rl, 10, 10)
r.system('cls')
and then it gives this
Why is the string not appending?
I read the code and tried to understand the goal of the program, and here are the things I figured out that is done wrong. I stated them and provided solutions for them.
1
The reason why ag=input() is written after the if statement is because you cannot execute the undo command without doing anything. So, you need to do something first, and only then you can undo.
So, the error is caused, which is shown from the terminal pic is because, by you entering 'undo' as the first command, and since it didn't find any if statement, it appended the string 'undo' to rl (Which is not what we want).
Solution:
First, don't enter 'undo' as the first command in the program. (Although, it's the most easy fix but not recommended practice.)
Second, Shift the ag=input(">>") command directly under two print statements and change the code in the if statement as follows:
if ag=='undo':
if len(rl) > 0: # Condition to check if rl is not empty
print(rl.pop(-1))
break # Use continue instead?
I changed list.pop(-1 to rl.pop(-1) as recommended by #oluwafemi-sule
Advice/Recommendation: Usually, when we undo things we don't exit the program/loop. We generally don't break the loop. We skip the rest of the execution, so I fell you should use continue instead of break in the above code.
2
Suppose someone entered 'exit' instead of the required argument, hence the program performs the required steps before closing. Now, we want the program to terminate, and here in your code there is no termination statement.
If we don't terminate the program, 'exit' will be appended to the rl and again it'll cause an error. Hence, your other if statement should have a break statement. That would break the loop and hence complete the execution.
if ag=='exit':
file = open(f'image{ra.randint(0,100001)}.imag')
for aa in rl:
file.write(f'{aa}\n')
file.close()
break

Python: how to envisage the interruption of a loop before its normal end

I have a loop running for quite a long time (several hours). It may be that the user, looking at the current results, considers the run iterations as sufficient and then wants to stop the loop before its natural end, but without interrupting the whole program (no "Ctrl+C") since some final results processing is necessary.
To do that, I added the possibility of creating a specific 'stop' file in the working directory. At each loop, the code verify if that file exists and, if that is the case, it end the loop. I do not know if this solution is efficient and whether better solutions exist.
Example
i = 0
while i < 1000 and not(path.isfile(path.join(self.wrkdir,'stop'))) :
DoSomeStuff
i += 1
FinalizingStuff
If the only reason for not using Ctrl+C is that you think it will stop all your program, then the best solution is to use it instead of watching the files.
Simply because you can catch this exception (it is called KeyboardInterrupt) in your code as any other and do whatever you want.
import time
try:
while True:
time.sleep(0.1)
except KeyboardInterrupt:
print('Ok, user is pissed with our loop, go further')
finally:
# if some resources need to be cleaned
pass
print('Here we are, nothing is lost')

Python: Bizarre issue with imported function within While Loop

So I have a bit of a conundrum. Let's start with the relevant fragment of my code.
from RECORD import recordSystem
recTime = 30 #Amount of time(seconds) I want to record the audio input
while True: #I want to keep this active while system is running
#Standard raspberry Pi input sensors.
if(GPIO.input(LedPin4) == GPIO.LOW and GPIO.input(LedPin5) == GPIO.HIGH:
recordSystem(recTime) #when condition is met run the code.
So the function I am trying to run comes from another script I wrote. And it works. It records analog audio and creates a .wav file in my project folder. The problem with this code is that it was working perfectly find yesterday and now is not. Nothing has been changed or touched. It just does not want to work. What happens is that the loop starts, and when the condition is met the function is launched properly and I get my "recording" notice in the compiler. Yet it NEVER stops recording.
When I just do the following outside of the loop:
recordSystem(recTime)
The function runs through properly without any problems. So it has to do something with calling the function inside the loop. Yet, it was working without any problems for a while.
Could anyone give me a best guest on what might be going on?
Much appreciated!
Adding a break statement after your recordSystem(recTime) should do the trick! I also fixed the indentation, and removed an extra ( from the code:
from RECORD import recordSystem
recTime = 30 #Amount of time(seconds) I want to record the audio input
while True: #I want to keep this active while system is running
#Standard raspberry Pi input sensors.
if GPIO.input(LedPin4) == GPIO.LOW and GPIO.input(LedPin5) == GPIO.HIGH:
recordSystem(recTime) #when condition is met run the code.
break

Python: Writing to file-->file empty

In a script data is written like so:
result = open("c:/filename.csv", "w")
result.write("\nTC-"+str(TC_index))
The .csv-file is filled with data in a while(1) loop.
I run the script in Eclipse and exit by hitting the stop button.
Unfortunately most of the time when I open the file it is completely empty.
Is there a way to fix that?
To ensure a content is flushed and written to file without having to close the file handle:
import os
# ...
result.write("\nTC-"+str(TC_index))
result.flush()
os.fsync(result)
But of course, if you break the loop manually there's no guarantee you won't break it between the write and the flush, thereby failing to get the last line. I'm unfamiliar with the Eclipse stop button but perhaps it stops execution by causing a KeyboardInterrupt exception to be raised. If so you could always catch that and explicitly close the file. Better still, use a with statement which will cause that to happen automatically:
with open("c:/filename.csv", "w") as result:
for TC_index in range(100): # or whatever loop
result.write("\nTC-"+str(TC_index))
# flush & fsync here if still necessary (but might not be)

Python: PySerial disconnecting from device randomly

I have a process that runs data acquisition using PySerial. It's working fine now, but there's a weird thing I had to do to make it work continuously, and I'm not sure this is normal, so I'm asking this question.
What happens: It looks like that the connection drops now and then! Around once every 30-60 minutes, with big error bars (could go for hours and be OK, but sometimes happens often).
My question: Is this standard?
My temporary solution: I wrote a simple "reopen" function that looks like this:
def ReopenDevice(devObject):
try:
devObject.close()
devObject.open()
except Exception as e:
print("Error while trying to connect to device " + devObject.port + ". The error says: " + str(e))
time.sleep(2)
And what I do is that if data pulling fails for 2 minutes, I reopen the device with this function, and it continues working well with no problems.
My program model: It's a GUI program, where the user clicks something like "Start", and that button does some preparations and runs a function through multiprocessing.Process() that starts with:
devObj = serial.Serial()
#... other params
devObj.open()
and that function then runs a while loop that keeps polling data with something like:
bytesToRead = devObj.inWaiting()
if bytesToRead != 0:
buffer = decodeString(devObj.read(bytesToRead))
#process buffer and push it to a list...
The way I know that the problem happened, is that devObj.inWaiting() Keeps returning zero... no matter how much data there's on the device!
Is this behavior expected and should always be considered whether it happens or doesn't happen?
The problem reduced a lot after not calling inWaiting() very frequently. Anyway, I kept the reconnect part to ensure that my program never fails. Thanks for "Kobi K" for suggesting the possible cause of the problem.

Categories