How do I capture Ctrl+C in line and exit the program as user enters it. I am using Python 3.7.3 on IPython 7.4.0 on spyder 3.3.3 on windows 64 bit machine with 8 GB RAM.
The most important thing is that when I run this program on windows powershell it works, this is happening only with spyder.
I tried using threads, KeyboardInterrupt, etc. but nothing works. I also saw lots of post regarding this but none is useful. Thing is that everytime python fails to capture Ctrl + C.
while True:
line = input()
if ('line contains Ctrl+C')
break
print(line)
print("Exiting")
I expect that after pressing Ctrl + C , program will print "Exiting" and stop execution.
The main thing there is what happens when you press Ctrl+C. It just stops. That being said, you might be able to except KeyboardInterrupt. Have you tried this?
import sys
try:
#Code Stuff Goes Here
except KeyboardInterrupt:
print(Exiting...)
sys.exit()
Related
I am running a script with python -i main.py. The script starts some C threads and python threads using threading module, then python code ends and it goes to a prompt. How can i prevent python from exiting if CTRL-D is accidentally pressed? I don't want to press CTRL-D by accident (already happened twice) and suddenly the interactive interpreter is down with all its threads.
I need the to still have access to the interactive interpreter. The goal is to start the C threads and python threads, then monitor them later from python.
I tried using readline and binding ^D to nothing, but it would still terminate python.
Example (main.py):
print("Init code for python thread")
print("Init code for c thread")
When running this with python -i main.py, after the second line is finished, i get the prompt >>>. If i am at the prompt and press CTRL-D, it will start a systemExit. I want to prevent that at all costs.
If you are waiting on input then you can wrap the input call in try/except. Remember that Ctrl-D is effectively EOF.
Therefore this might be a useful pattern:
while True:
try:
v = input('Type something: ')
break
except EOFError:
print('You typed CTRL-D')
print(f'You typed {v}')
I want KeyboardInterrupt part run by clicking red button(stop) in Pycharm, but it doesn't work.
I tried it in Anaconda3 prompt, and KeyboardInterrupt worked.
However, when I try it in Pycharm by clicking red button, it doesn't work.
import time
try:
while True:
time.sleep(1)
print(3)
except KeyboardInterrupt:
print(5)
'Process finished with exit code -1' pops up and nothing happened.
In this case, you use try-except. So when you stop your program it print 5 in your pycharm console.
Python fails to quit when using Ctrl-C in Powershell/Command Prompt, and instead gives out a "KeyboardInterrupt" string.
Recently I've reinstalled Windows 10. Before the reinstall Ctrl-C quit python (3.5/2.7) fine, with no output.
Does anyone know why this has started happening? Whether it's just a simple setting?
The only difference I can think of is I'm now on python 3.6. Ctrl-D works in Bash on Ubuntu on Windows, and Ctrl-C works fine in an activated anaconda python2 environment for quitting python.
I had this issue with Windows 10 Pro Build 18363 and Python 3.8.1. I was running some python scripts and was unable to stop some with CTRL + C, but CTRL + BREAK worked every time. The Windows Docs had this to say:
The CTRL+C and CTRL+BREAK key combinations receive special handling by console processes. By default, when a console window has the keyboard focus, CTRL+C or CTRL+BREAK is treated as a signal (SIGINT or SIGBREAK) and not as keyboard input...
CTRL+BREAK is always treated as a signal, but an application can change the default CTRL+C behavior in two ways that prevent the handler functions from being called:
The SetConsoleMode function can disable the ENABLE_PROCESSED_INPUT input mode for a console's input buffer, so CTRL+C is reported as keyboard input rather than as a signal.
When SetConsoleCtrlHandler is called with NULL and TRUE values for its parameters, the calling process ignores CTRL+C signals. Normal CTRL+C processing is restored by calling SetConsoleCtrlHandler with NULL and FALSE values. This attribute of ignoring or not ignoring CTRL+C signals is inherited by child processes, but it can be enabled or disabled by any process without affecting existing processes.
Thus, CTRL + C seems to be a SIGINT and its actions can be modified by the program you are running. It seems that Python on Windows has been coded in such a way that CTRL + C is being processed as keyboard input rather than the SIGINT we are expecting. Fortunately for me I have the CTRL + BREAK keys on my keyboard and this works every time.
For those of you who dont have BREAK on your keyboard, you can use the Windows On Screen virtual Keyboard.
Press win key + r to open the run application program.
Type oskand press ok
On the virtual keyboard, press ctrl + ScrLk and this should kill the program.
This stack thread has some other methods you can try if ctrl + ScrLk doesnt work on the virtual keyboard.
You can type
CTRL + Z,
then hit ENTER to exit python from powershell.
Powershell Screenshot
This is a bug that recently appeared in Windows 10 Insider build 15002.
A work around is to change the Mapped Keys from Ctrl C to something like Ctrl K
If you are not familar how to do this, You can look up or at stty -a
You can run this command on each bash session that will map your Terminate to Ctrl + K
stty intr \^k
As a TEMP solution you could include this in your Bashrc so it is executed on each new session
This bug has been reported already on Github #1569
In my case, I found out that right ctrl + c does the trick in anaconda3 powershell - so no remapping necessary - I'm on Windows 10.
That worked like magic
If you have a laptop with Fn key, tap:
Ctrl + Fn + S
Source:
https://www.dell.com/community/Laptops-General-Read-Only/break-key-alternative/td-p/3826467
When you press Control C, a KeyboardInterrupt exception is thrown. If it isn't stopping the code, the best thing to do is to add a try statement into your code which catches KeyboardInterrupt
try:
....
except KeyboardInterrupt:
exit()
The code is just off the top of my head so sorry if something is wrong.
EDIT: Ctrl Break or on some keyboards Ctrl Pause instantly stops python code apparently.
Hitting Esc button on the upper corner of the keyboard seems to work for me on Windows-7, inside Spyder with numpy running, for Python 3.+
It broke the infinite ...: on an erroneous syntax in the interactive script
When I used to press Ctrl-C, python was quit normally without any output.
I really don't remember when I can quit python with Ctrl + C. In my memory, Ctrl + C always give me KeyboardInterrupt.
I also counldn't find an answer explaining why Ctrl + C can't quit the python in shell. FYI, Ctrl + D and Ctrl + \ can quit python for different reasons. See #Gilles's answer here. https://superuser.com/questions/169051/whats-the-difference-between-c-and-d-for-unix-mac-os-x-terminal
But I think how to handle Ctrl + C is merely a decision of the program. Yes, I think it totally depends on how the program would like to handle it. See the example I write below.
test.c
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
static void ctrlC_Handler(int sig){
if(sig == SIGINT){
printf("(:KeyboardInterrupt:)\n");
printf(">>>");
signal(SIGINT, ctrlC_Handler);
}
}
static void welcome(){
printf("Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15)\n");
printf("[GCC 7.3.0] on linux2\n");
printf("Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n");
printf(">>>");
fflush(stdout);
}
int main(){
welcome();
signal(SIGINT, ctrlC_Handler);
for(;;){
pause();
}
return 0;
}
compile it with gcc test.c and execute it ./a.out. Try pressing Ctrl + C, you can see at least it mimics the behaviour(output) of the python program when you input Ctrl + C.
So, in my opinion, it's nothing special, but a human/programmer/author's decision on how to handle it.
This question may have been asked a couple of times but I cannot seem to find it.
Basically I am just learning Python and I am on Windows, this means I double click the .py file and open it. This works great until an error appears, at which point Python calls exit and the window closes.
One way, of course, to get around this is to use the cmd program in Windows and run the Python program from there, however, is there a way to fix it so that my application doesn't bail out and close as soon as it hits an error if I open it from Windows Explorer?
while(True):
try:
number = input('Enter a number: ')
if(is_int(number) is False):
print('Please actually enter a number')
if(number > 0):
answer = input('Oh Noes you really want that?')
if(answer == 'yes'):
sys.exit(0);
except KeyboardInterrupt:
sys.exit(0)
except Exception as e:
input('')
In order to keep your program intact, e.g. to not introduce unwanted catch-em-all exception handling (aka pokemon handling) there are at least three options:
Use any console terminal, e.g. built-in cmd or powershell or any third-party console apps out there.
Use any IDE: pycharm, IDLE (python windows installer by default sets it up) or whatever you have capable of running python code.
Use text editor plugins for running python code. At least notepad++ and sublime text are capable of doing so.
I would recommend starting with option 1 for starters, then slowly move to option 3 for small scripts and projects, and option two for larger ones.
I you put an input function at the bottom of your script then it will hang there until you hit enter or close the command prompt. If you call an exit function put it immediately before the exit function is called. Otherwise place it at the bottom of the script.
Also I assume you have defined is_int already in your script?
What would you think it should do?
Python is drawing the window you see, if python crashes, the windows is going away.
You can run it trough cmd, or within an IDE. (like IDLE, that has some problem though when it comes to GUI)
Otherwise, add something like this at the end of the file
try:
run()
except Exception as inst:
print type(inst), inst.args
#it prints the exception
print sys.exc_traceback.tb_lineno
#if you want the line number where the error occurred in the source code
raw_input()
inst is the exception instance, you can see the type and the list of arguments.
Then with the sys module you can also see the line where the error occurred in the code.
This way every error will be handled and displayed before closing
Is this the right way?
No. You should really be using ad IDE (like Eclipse with PyDev or PyCharm).
After #SeçkinSavaşçı's extremely useful comment at the start:
The most common way is to let it wait for an input, then ignore the input and terminate the script.
Which took me a second to understand I went in search of how to do this, so first I saw to stop the script and used:
while(True):
try:
# Application code here
except:
input('')
Which worked really well to catch all errors, which unlike in PHP (which I have become comfortable with unfortunately) are all exceptions.
So the next part was to to tell me what error had occured and how to fix it, I needed a backtrace. It just so happens that the Python docs gave me the answer right here: http://docs.python.org/2/library/traceback.html#traceback-examples in an easy to see example:
exc_type, exc_value, exc_traceback = sys.exc_info()
print(traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout));
Add that above the input('') and I had my perfect error handling showing me everything I needed.
Thanks all,
Try import time and time.sleep(). Also, I recommend you to use IDLE or Geany. I've been using them and they work out well.
I have written a programme by python which is successfully tested under eclipse.Then I used pyinstaller to excute it as a .exe file. When the programme raise the exception ,the cmd window will quit immediately. I want to stay in this window to take a good look at this exception. How can I do it ? Thank you.
As Ms Turdy mentioned, you should run it in a command prompt or terminal first, if it will have the same behavior as the exe.
You can execute a python script with python -m pdb script.py and it will enter into the debugger. You run it by pressing C for continue, then it will break when it raises the exception.
That is because the python script has finished its job. You can do this:
import time
# your code
...
time.sleep(20)
This will give you 20 seconds to see the result. And after 20 s, the cmd window will remain 20 s for you to see the result. You can change the time for your requirement.
You can try raw_input to hold the screen:
import traceback
try:
# do something dangerous
except Exception, e:
print 'Error:', e
print traceback.format_exc()
raw_input('Input anything to end...')