I ran into a particularly infamous problem: I'm creating a sort of console program on Python 3.6, but when I write a command that is not 'exit' or 'shutdown', if this command is incorrect, the console enters the loop and keeps trying to execute the incorrect command by spamming in the console the error message defined with the 'except' instruction.
I tried to delete the 'try' and 'except' statement, but in this way, if the command is incorrect, the program is interrupted and the closing command is not executed.
P.S. I forgot to write that with the 'try-except' instruction, if i press enter without writing anything, the bug leaves the same.
Machine code - Start
import os
print("$ ", end="") #No end-line
console_standard_input = input()
while console_standard_input != ".shutdown":
if (console_standard_input == "exit"):
print("Shutting down machine...")
sys.exit(-1)
try:
machine_exec_script_path_complete = "Disk\{0}".format(console_standard_input)
os.system(machine_exec_script_path_complete)
except:
print("Unable to exec this function - Error")
print("")
print("$ ", end="")
#Machine code - Stop
I haven't been able to find a solution yet.
I'm not very good at Python, so I wanted to ask the help of an expert.
Try:
import os
print("$ ", end="") #No end-line
console_standard_input = input()
while console_standard_input != ".shutdown":
if(console_standard_input == "exit"):
print("Shutting down machine...")
sys.exit(-1)
try:
machine_exec_script_path_complete = "Disk\{0}".format(console_standard_input)
os.system(machine_exec_script_path_complete)
except:
print("Unable to exec this function - Error")
print("")
print("$ ", end="")
console_standard_input = input()
Explanation - if you wish to keep evaluating input - you have to put input there explicitly. Assigning input() to a variable assigns only it's value (user input), not the whole operation i.e. it doesn't force it to repeat, whenever the variable is reevaluated...
Related
After searching SO it appears most posts regarding Ctrl^C are about exiting the program, and I would like to just abort the input( ... ) statement but not the program itself. Here is the key code from the application:
import readline
def do_something() # ... see method call below
command_str = readline_input(self.shell_prompt(), default_prompt)
command_str = command_str.strip()
def readline_input(prompt, prefill=""):
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return input(prompt)
finally:
readline.set_startup_hook()
How do I bind Ctrl^C to just exit that input( .. ) prompt (as if I had entered nothing) vs. exiting the program?
IDK if this is what you are asking for but with the try function you have you can use
except KeyboardInterrupt:
exit()
I'm just beginning with programming(python3), using the information available on Internet. Right now I'm learning how to use try/except. My problem is that the code I wrote runs fine in the command prompt of windows 10, but not in the shell(Atom/Hydrogen) where it throws an error(line 6, NameError) because I didn't defined the variable "fish", I know that usually happened the other way around but I just want to understand if I'm making a mistake. The code is as follows:
>try:
>> fish = int (input("please enter your age "))
>except:
>> print("That's not a number ")
>> exit(0)
>if fish <= 15:
>> parentLicense = input ("have one of your parents have a license? (yes/no) ")
>> if parentLicense == "yes":
>>> print ("You can fish")
>> else:
>>> print("So sad, you or one of your parents need a license")
Hi Chiron and welcome to the community. The reason you are getting an undefined error is because fish can be undifined under certain circumstances in the try statement.
You should use
try:
# try stuff
except ValueError:
# do stuff when theres an error
else:
# stuff if try stuff works
else is only called if no exception is raised. I would avoid using bare except too as it can cause issues and its not good practice.
I need to take multiple line input from user - works with a while loop, but have an issue starting another input() as the EOF gets "passed" over to the new input()
I've tried using a combination of the sys stdin, and func() but, not sure why it's happening.
while True:
try:
list = input()
except EOFError:
break
input('input2:')
1) Don't use list as a variable name. That is a reserved word in python.
2) You can catch a KeyboardInterrupt which will stop the loop after a Ctrl + C and EOFError which catches a Ctrl + D:
while True:
try:
list = input()
except (EOFError, KeyboardInterrupt):
break
input('input2:')
Alternatively you can prime your loop and let the loop exit on a set condition:
my_input = input()
while my_input: # Break if nothing was inputted
print(f"Inputed: {my_input}")
my_input = input()
input('input2:')
what I want is something like this:
The first file just prints as soon as the 2nd has read
# a.py
print('pepe')
# wait till the other had read
print(23)
The second program uses data from the later
# b.py
name = input()
age = int(input())
print('Hi ' + name + ', you are ' str(age))
So I can see in the console:
Hi pepe, you are 23
I want to do this because, I waste a lot of time typing in the console. And I want to do it automatically.
Just in case, I browsed for this thing a long time, but no idea, that is why I decided to ask here.
A couple of different ways.
1) while True:
an infinite loop that requires you to use some sort of
while True:
cmd = input("type something")
if cmd == 'e':
do something
elif cmd == 'f':
do something else
else:
do that last thing
2) input("press enter to continue")
input('press enter to continue')
Hopefully that gets you what you need...
You can also learn more here: How do I make python to wait for a pressed key
I get that it's a very difficult thing to pick up on in the background, but what I'm looking for is a program that records a keypress, and how much time it takes between keypresses. None of what I have looked into was able to record in the background, or actually work.
EDIT:
import win32con, ctypes, ctypes.wintypes
def esc_pressed():
print("Hotkey hit!")
ctypes.windll.user32.RegisterHotKey(None, 1, 0, 0xDD) # this binds the ']' key
try:
msg = ctypes.wintypes.MSG()
ctypes.windll.user32.GetMessageA
while ctypes.windll.user32.GetMessageA(ctypes.byref(msg), None, 0, 0) != 0:
if msg.message == win32con.WM_HOTKEY:
esc_pressed()
ctypes.windll.user32.TranslateMessage(ctypes.byref(msg))
ctypes.windll.user32.DispatchMessageA(ctypes.byref(msg))
finally:
ctypes.windll.user32.UnregisterHotKey(None, 1)
This allows for the program to work in the background, but it takes the inputted character you bound, instead of picking up on it. I still need to make sure the inputted character gets to the window with focus.
You probably have to catch the key and then simulate the same key press again. Try checking out Python Keyboard module for that.
EDIT: Added code sample.
import keyboard, time
def KeyPressSample(startkey='tab', endkey='esc'):
while True: # making a inifinte loop
try:
if keyboard.is_pressed(startkey):
time.sleep(0.25)
print("%s Key pressed." % startkey)
elif keyboard.is_pressed(endkey):
print("%s Key pressed." % endkey)
break
except KeyboardInterrupt:
print('\nDone Reading input. Keyboard Interupt.')
break
except Exception as e:
print(e)
break