I would like to know how to leave a loop from the terminal, otherwise when closing it...
Thanks!
I tried 'exit', 'leave' and others keywords like that
In Mac and Windows: control + C. In general it terminate a process.
try adding keyboard Interrupt exception
try:
while True:
pass
except KeyboardInterrupt, e:
print "Stopped"
raise
Related
Python 3.10 in macOS terminal
I kick off this simple script in macOS terminal, which runs infinitely (so please be warned when running it):
import itertools
for i in itertools.count(start=1):
try:
p = pow(2,i)
print(p)
except KeyboardInterrupt:
print("Loop terminated")
raise
Yet clicking on the keyboard does not terminate the loop.
What am I missing?
Thanks to everyone for the clarification. The problem is I was under the assumption that KeyboardInterrupt would respond to any key pressed. It actually only responds to Ctrl-C. Everything works as expected when using Ctrl-C.
There seem to be many, many threads here and Google hits re use of exit, quit, os._exit(), sys.exit() in Python, but none I've found play nicely with IPython.
When I use most of them I get:
UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
I'm trying to debug in Python - when a certain condition is met I want Python to stop executing and return to the Python command line so I can examine global variables, etc.
How to do that?
For now I've done this, which works when I hit Ctrl-C, but there ought to be a way that doesn't require the Ctrl-C.
def halt():
while True:
time.sleep(0.2)
Have you tried using the Python Debugger?
import pdb
while doing_something:
if condition:
pdb.set_trace()
If you want to manually control when the loop exits, you can try:
while doing_something:
try:
do_something()
except KeyboardInterrupt:
pdb.set_trace()
I want to run a function after I "command c" on terminal. I am scraping some data onto a file using python, and then I want to immediately close and push the file to google drive when I terminate the scraping process.I have written two different files for scraping and pushing but I would like to do this all in one file. How do I indicate the change of "command c" in python? If command c..do this...
Any help would be super useful! Thanks!
The sequence ctrl+C (or command+C on Mac) causes a KeyboardInterrupt exception to be raised.
You can simply catch this exception, with a simple try-except.
For instance, the following code will run a dummy work that takes some time, and on a ctrl+C, will stop that work and print its current state.
import time
try:
for i in range(100):
time.sleep(1)
except KeyboardInterrupt:
print(i)
Note that, as specified in the doc, the KeyboardInterrupt exception inherits from BaseException but not from Exception.
As a consequence, a except Exception clause would not catch a KeyboardInterrupt, while a except BaseException would catch both KeyboardInterrupt and Exception.
What you need is atexit module https://docs.python.org/2/library/atexit.html
create a handler function to do the persisting part. register it with atexit to run at the exit.
def goodbye(name, adjective):
print 'Goodbye, %s, it was %s to meet you.' % (name, adjective)
import atexit
atexit.register(goodbye, 'Donny', 'nice')
My Python try/except loop does not seem to trigger a keyboard interrupt when Ctrl + C is pressed while debugging my code in PyCharm. (The same issue occurs when using Ctrl + C while running the program, but not in the PyCharm Python console.)
My code look like this:
try:
while loop:
print("busy")
except KeyboardInterrupt:
exit()
The full code can be viewed here. The code above produces the same error.
I know this is an old question, but I ran into the same problem and think there's an easier solution:
In PyCharm go to "Run"/"Edit Configurations" and check "Emulate terminal in output console".
PyCharm now accepts keyboard interrupts (make sure the console is focused).
Tested on:
PyCharm 2019.1 (Community Edition)
From your screen shot it appears that you are running this code in an IDE. The thing about IDEs is that they are not quite the same as running normally, especially when it comes to handling of keyboard characters. The way you press ctrl-c, your IDE thinks you want to copy text. The python program never sees the character. Pehaps it brings up a separate window when running? Then you would select that window before ctrl-c.
PyCharm's Python Console raises the exception console_thrift.KeyboardInterruptException on Ctrl-C instead of KeyboardInterrupt. The exception console_thrift.KeyboardInterruptException is not a subclass of KeyboardInterrupt, therefore not caught by the line except KeyboardInterrupt.
Adding the following lines would make your script compatible with PyCharm.
try:
from console_thrift import KeyboardInterruptException as KeyboardInterrupt
except ImportError:
pass
This would not break compatibility with running the script in a terminal, or other IDE, like IDLE or Spyder, since the module console_thrift is found only within PyCharm.
If that comment doesn't solve your problem, (from #tdelaney) you need to have your shell window focused (meaning you've clicked on it when the program is running.) and then you can use Control+C
You can also use PyCharm's Python console and use Ctrl + C, if you catch the exception that PyCharm raises when Ctrl + C is pressed. I wrote a short function below called is_keyboard_interrupt that tells you whether the exception is KeyboardInterrupt, including PyCharm's. If it is not, simply re-raise it. I paste a simplified version of the code below.
When it is run:
type 'help' and press Enter to repeat the loop.
type anything else and press Enter to check that ValueError is handled properly.
Press Ctrl + C to check that KeyboardInterrupt is caught, including in PyCharm's python console.
Note: This doesn't work with PyCharm's debugger console (the one invoked by "Debug" rather than "Run"), but there the need for Ctrl + C is less because you can simply press the pause button.
I also put this on my Gist where I may make updates: https://gist.github.com/yulkang/14da861b271576a9eb1fa0f905351b97
def is_keyboard_interrupt(exception):
# The second condition is necessary for it to work with the stop button
# in PyCharm Python console.
return (type(exception) is KeyboardInterrupt
or type(exception).__name__ == 'KeyboardInterruptException')
try:
def print_help():
print("To exit type exit or Ctrl + c can be used at any time")
print_help()
while True:
task = input("What do you want to do? Type \"help\" for help:- ")
if task == 'help':
print_help()
else:
print("Invalid input.")
# to check that ValueError is handled separately
raise ValueError()
except Exception as ex:
try:
# Catch all exceptions and test if it is KeyboardInterrupt, native or
# PyCharm's.
if not is_keyboard_interrupt(ex):
raise ex
print('KeyboardInterrupt caught as expected.')
print('Exception type: %s' % type(ex).__name__)
exit()
except ValueError:
print('ValueError!')
Here is working normally, since i put a variable "x" in your code and i use tabs instead spaces.
try:
def help():
print("Help.")
def doStuff():
print("Doing Stuff")
while True:
x = int(input())
if x == 1:
help()
elif x == 2:
doStuff()
else:
exit()
except KeyboardInterrupt:
exit()
Try shift + control + C. It worked for me.
Make sure the window is selected when you press ctrl+c. I just ran your program in IDLE and it worked perfectly for me.
One possible reason if <Strg+C> does not stop the program:
When a text is marked in the shell, <Strg+C> is interpreted as "copy the marked text to clipboard".
Just unmark the text and press <Strg+C> again.
I want to stop a Python script on seeing an error message.
I dont want any error message on shell like exit().
How to do it ???
When you send CTRL+C to a Python script, it raises the KeyboardInterrupt exception, so you can do something like
try:
... Work goes here ...
except KeyboardInterrupt:
sys.exit(0)