Python 3 cause Ctrl-C to exit input only, not program - python-3.x

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()

Related

Process Still running in background after python script converted to exe with pytoexeconverter

Is there a way properly kill a process once the application exits? If yes how can I integrate this in my python script so that it does the job automatically if it exits? I got this code to restart my app when it craches but since the process is still running in the backgroung it doesn't work. Cheers
proccess = 'app'
def checkIfProcessRunning(process):
'''
Check if there is any running process that contains the given name processName.
'''
#Iterate over the all the running process
for proc in psutil.process_iter():
try:
# Check if process name contains the given name string.
if process.lower() in proc.name().lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False
def ex():
os.system('TASKKILL /F /IM Trailling.exe')
#atexit.register(ex)
def start_process():
return os.system(cmd)
try:
start_process()
atexit.register(ex)
while True:
if checkIfProcessRunning('process'):
print("Process is running")
time.sleep(5)
else:
print("Process is not running")
start_process()
except Exception as e:
print(e)
At any exit point for your program, simply add a function to kill the process. You're already checking if the process is running, and you can use the same interface to kill the process.
I would recommend modifying checkIfProcessRunning to, instead of returning True or False, return the process if it exists, or return None otherwise:
def checkIfProcessRunning(process):
'''
Check if there is any running process that contains the given name processName.
'''
#Iterate over the all the running process
for proc in psutil.process_iter():
try:
# Check if process name contains the given name string.
if process.lower() in proc.name().lower():
return proc
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return None
This should still work with your if checks (by default, any non-None object registers as truthy), and it makes it much easier to build a kill method, using the process's .kill() method:
def killProcessIfRunning(process):
'''
Kill the process, if it's running.
'''
proc = checkIfProcessRunning(process)
if proc:
proc.kill()
# alternatively, use proc.terminate() if you want to be more hardcore and are not on Windows
# or proc.send_signal() with SIGSTOP or something
Then, just call the kill method at any exit point for your program (since you've used atexit, this should just be the ex() method regardless):
def ex():
killProcessIfRunning('process') # replace with the name of the same process you started with
os.system('TASKKILL /F /IM Trailling.exe')
The good news about the error that I commented about in my previous answer is that when you put a working app in the right folder and take out the double '' is that the restart script works and it restarts the program indefinitely with the following script:
import time
import psutil
import os
app = 'Raiseexception'
cmd = r"C:\Users\g\Desktop\API\Raiseexception.exe"
def checkIfProcessRunning(app):
'''
Check if there is any running process that contains the given name processName.
'''
#Iterate over the all the running process
for proc in psutil.process_iter():
try:
# Check if process name contains the given name string.
if app.lower() in proc.name().lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return False
def ex():
os.system('TASKKILL /F /IM Raiseexception.exe')
def start_process():
return os.startfile(cmd)
try:
start_process()
while True:
if checkIfProcessRunning(app): #check for double ' '
print("Process is running")
time.sleep(5)
else:
print("Process is not running")
start_process()
except Exception as e:
print(e)
Cheers,
Lrd

Try-except bug in a while

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...

Function that to exit from other function

I wanted to create to a function which, when called in other function it exits the previous function based on the first function's input.
def function_2(checking):
if checking == 'cancel':
# I wanted to exit from the function_1
def function_1():
the_input = input("Enter the text: ")
function_2(the_input)
I wanted the code for the function_2 so that it exits from function_1, I know that I can put the if statement in function_1 itself but ill use this to check more than one in input in the same function or even in different function I cant put the if block everywhere it will look unorganized so i want to create a function and it will be convenient to check for more than one word like if cancel is entered i wanted to exit the programm if hello is entered i wanted to do something, to do something its ok but to exit from the current function with the help of other function code please :) if any doubts ask in the comment ill try to give you more info im using python 3.x.x on Windows8.
Why not simply:
def should_continue(checking):
if checking == 'cancel':
return False
return True
def function_1():
the_input = input("Enter the text: ")
if not should_continue(the_input):
return
This is the best solution I think.
Another alternative is to raise an Exception, for example:
def function_2(checking):
if checking == 'cancel':
raise KeyboardInterrupt
def function_1():
the_input = input("Enter the text: ")
function_2(the_input)
try:
function_1()
except KeyboardInterrupt:
print("cancelled by user")

How to end a while loop containing a time.sleep?

Say I got a code like this:
import time
try:
while True:
print("Hello World")
time.sleep(10)
except:
print("Ctrl+z was pressed") #Doesn't get executed
When I try to execute this code in python 3, the stuff in my except block does not execute. What can I do?
you will always be stuck in the while loop, as the condition is always True. you will never exit the try condition and so never execute the except block.
If I am correct, crtl+z does only make the program sleep, so is no termination signal like crtl+c, which would break the loop and get the except block to execute.

How to read keypresses in the background in python

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

Resources