Disabling KeyboardInterrupt after it has been used once - python

Cont = 1
while Cont == 1:
try:
while Cont == 1:
counter = counter + 0.1
counter = round(counter, 1)
print(counter)
time.sleep(0.1)
if counter == crashNumber:
Cont = 0
except KeyboardInterrupt:
Multiplier = counter
Here the counter will continue to count up unitl it reaches the crashNumber, when Ctrl + C is pressed, it will take the number that the counter is at and use it for the Multiplier to be used later.
However I only want to give the user the chance to press this once, then it is disabled. Is there any way that this can be done?

The KeyboardInterrupt exception will be thrown whether you want it or not: the solution, then, is to deal with the exception in different ways in your except block. My chosen implementation will use a simple boolean value that starts as True and is set to False on the first interruption:
import time
allow_interrupt = True
while True:
try:
time.sleep(1)
print ('...')
except KeyboardInterrupt:
if allow_interrupt:
print ('interrupted!')
allow_interrupt = False
Let me know if this addresses your use case.

Related

Understanding how a try except logic works within two while loops

I'm having trouble understanding the mechanism of my code. I want to retrieve the realtime price data of a crypto from an exchange and print it every second, while creating a retry mechanism that catches an exception when it occurs.
while True:
try_cnt = 10
while try_cnt > 0:
try:
price = get_current_price(symbol) # function imported from elsewhere
print(price)
time.sleep(1)
try_cnt = 0
break
except Exception as e:
print(e)
try_cnt -= 1
This is how I have it set up but I'm having trouble follow the logic. This is how I see it as of now. After the code has been run:
Price is retrieved
try_cnt is set to 0 and the second while loop is broken
The next second, try_cnt is reset to 10 and price is retrieved
try_cnt is set to 0 again and the second while loop is broken
repeat of this process
Am I understanding this correctly?
EDIT: the reason why I have a while loop outside is that I have other things that are going on at specific times besides the part I mentioned here. The part that I mentioned is supposed to be running all the time every second. For example,
while True:
if now.hour == 0 and now.minute == 0 and now.second == 0:
A = functionA(x,y)
try_cnt = 10
while try_cnt > 0:
try:
price = get_current_price(symbol) # function imported from elsewhere
print(price)
time.sleep(1)
try_cnt = 0
break
except Exception as e:
print(e)
try_cnt -= 1
I think that you are understanding everything just fine, but the code itself is a little silly and redundant. For example, setting try_cnt to 0 and then following that with break is pointless - both lines do the same thing. And unless there is some significance to the variable try_cnt that is not present within the code you posted, its existence seems pretty much useless to me. Here's code that does the exact same thing as the code above, but without the redundancies:
while True:
try:
price = get_current_price(symbol)
print(price)
time.sleep(1)
except Exception as e:
print(e)
In response to your edit, the while True loop encompassing everything makes a lot more sense. However, this means that your code isn't doing what you want it to do. The outer while loop ensures that even if try_cnt reaches 0, try_cnt will just be reset to 10 on the next pass and it will be as if no Exceptions ever occurred (besides the ten error messages in the console). If you want that inner while loop to stop executing when ten Exceptions occur, you need to place the try_cnt = 10 statement outside of both while loops like so:
try_cnt = 10
while True:
if now.hour == 0 and now.minute == 0 and now.second == 0:
A = functionA(x,y)
while try_cnt > 0:
try:
price = get_current_price(symbol)
print(price)
time.sleep(1)
try_cnt = 10
break
except Exception as e:
print(e)
try_cnt -= 1

Possible memory leak in Python?

I'm experiencing an issue when calling a function inside a while loop.
The purpose of the while loop is to perform an action ,but it can only perform this action if a certain threshold appeared. This threshold is a result from another function.
When running this for the first time ,everything works ok. No threshold -no run.
The problem is ,that this threshold is affected by other parameters ,and when it changes ,it usually blocks the main program from running.
But ,at certain times, which I cannot pinpoint precisely when ,there's a "slip" and the threshold does not prevent the main program from running.
My question is ,could there be a memory leakage of some sort?
Code is below ,thanks.
def pre_run_check():
if check_outside() != 1:
return (0)
else:
return(1)
if __name__== '__main__':
while True:
time.sleep(0.5)
allow_action = None
while allow_action == None:
print ("cannot run")
try:
allow_action = pre_run_check()
except:
allow_action = 0
else:
if allow_action == 1:
print ("running")
#take action of some sort##
allow_action = None
def pre_run_check():
if check_outside() != 1:
return False
else:
return True
while True:
time.sleep(0.5)
allow_action = pre_run_check()
while not allow_action:
print ("cannot run")
try:
allow_action = pre_run_check()
if allow_action :
print ("running")
#take action of some sort##
allow_action = False
#Actualy need wait end of subprocess, Otherwise got some corrupted data/handle
break
except:
allow_action = False
time.sleep(.5)
This point is how to generate an sequential Process
Hope its helps.

How to repeat a step in a loop if an action fails?

In the case I am looping into a list, where for value msg_list = 0 it will execute action(0), usr). This action can fail for a determined user, I should choose aother user if it happens, perform all the actions related to the user
How can I do to repeat action[0] if it fails?
for msg in range(len(msg_list)):
# in this case msg = 0
usr = select_random_user()
multiple_actions_for(usr) # This are lots of code lines I don't want to repeat!!
try:
action(msg, usr)
more_actions(usr.related_stuff)
except Exception as e:
go_back_to(msg =0 instead of looping into msg=1) # this is what I want to do
How can I do to get that? Repeat the loop for msg = i instead of passing to msg = i + 1?
Put your code into the endless while-loop with exiting from it if try was successful:
for msg in range(len(msg_list)):
while True:
usr = select_random_user()
multiple_actions_for(usr)
try:
action(msg, usr)
more_actions(usr.related_stuff)
except Exception as e:
continue
else:
break
It really depends. Is it okay to go back to the beginning of the loop? If so, you can call "continue", which stops the current iteration, and restarts the loop. Otherwise, I don't think there's something similar to a goto in Python, no. It's a very structured language.
Try using while loop instead of for loop. The idea is as shown bellow:
bool still_looping = True
msg = 0
while still_looping:
usr = select_random_user()
multiple_actions_for(usr)
try:
action(msg, usr)
more_actions(usr.related_stuff)
if (msg < len (msg_list)):
msg += 1
except Exception as e:
# Do whatever you want here. msg was not incremented
if (msg == len(msg_list))
still_looping = False #verify if this was the last execution

How to reset input from keyboard after delay?

Simple "input" in python:
code = input("Entrer your code...")
processCode(code)
I need to ask the user for a password on a usb keyboard but without a screen (so the user doesn't see what he is typing). The text here is just for some tests. The sending is validated by the Enter key of course.
To make sure that the input is always blank when the user starts typing and sends his code, I will need to add a condition to this input.
I would need some sort of time counter which starts after each character entered and if the Enter key is not pressed for 10 seconds, the input will be automatically reset.
Here is an example of code that approximates your question. You can improve it or take inspiration from it:
import keyboard
import time
from threading import Thread
start_time = time.time()
saved_pwd = False
stop_thread = False
def dedupe(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
def count_time():
global saved_pwd, start_time
while True:
lap_time = round(time.time() - start_time, 2)
global stop_thread
if lap_time >= 10:
print("Please Re-enter the password")
saved_pwd = True
break
elif stop_thread:
break
password = []
Thread(target=count_time).start()
while saved_pwd is False:
key = keyboard.read_key()
start_time = time.time()
if key == 'enter':
saved_pwd = True
stop_thread = True
else:
password.append(key)
print("Your pwd: ", ''.join(dedupe(password)))

python while loop break

I am trying to make an on/off switch for my program:
(see after the ### for what I'm talking about)
while 1:
str = raw_input("insert your word: ")
n = input("insert your scalar: ")
def string_times(str, n):
return n * str
print string_times(str, n)
###
def switch(on,off):
raw_input("On or off? ")
if switch == "on":
continue
if switch == "off":
break
switch(on,off)
I get a continue not in loop error. Basically, I want to create an on or off switch after the program runs once. What do I fix?
You cannot use break and continue in a nested function. Use the return value of the function instead:
def switch():
resp = raw_input("On or off? ")
return resp == "on":
while True:
# other code
if not switch():
break
Note that there is little point in defining your functions in the loop. Define them before the loop, as creating the function object takes some performance (albeit a small amount).
The switch() function needs no arguments (you didn't use them at all), and the continue is also not needed. If you didn't break out of the loop, it'll just continue from the top when you reach the end.
You only need continue if you want the loop to start at the top again skipping the rest of the code in the loop:
count = 0
while True:
count += 1
print count
if loop % 2 == 0:
continue
print 'We did not continue and came here instead.'
if count >= 3:
break
print 'We did not break out of the loop.'

Categories

Resources