How to stop/terminate a python script from running?
Asked Answered
C

19

174

I wrote a program in IDLE to tokenize text files and it starts to tokeniza 349 text files! How can I stop it? How can I stop a running Python program?

Caliph answered 5/11, 2013 at 4:46 Comment(3)
ctrl+c should kill it. Alternatively, kill -9 itAstrea
Many answers here are platform-specific. Search for your platform (Windows, Linux, Mac, something else?)Camelliacamelopard
So many friends spent effort to write answers, but none got accepted, yet :-(Awl
B
80

To stop your program, just press Control + C.

Balzer answered 5/11, 2013 at 4:49 Comment(5)
This method worked on my windows laptop, but on my linux desktop, it showed ^C in the terminal and the system monitor showed python is still using a lot of CPU...Overtop
Is it possible to resume the script after stopping it?Madalena
@Madalena If you want to pause the process and put it in the background, press Ctrl + Z (at least on Linux). Then, if you want to kill it, run kill %n where "n" is the number you got next to "Stopped" when you pressed Ctrl + Z. If you want to resume it, run fg.Molina
Does not work if you have a general except: clause in the program. The except: catches the interrupt, does something (or not), and then the program merrily continues.Molar
@Molar Your general except should have an special except for the error trown by Ctrl+C. Anyway, general excepts are usually discouraged.Marchland
S
210

You can also do it if you use the exit() function in your code. More ideally, you can do sys.exit(). sys.exit() which might terminate Python even if you are running things in parallel through the multiprocessing package.

Note: In order to use the sys.exit(), you must import it: import sys

Sauls answered 1/12, 2015 at 20:27 Comment(2)
Note: I could find examples in which sys.exit(1) doesn't stop the process. I basically have multiple threads and each of them blocks on external processes started by Popen. I need a nuclear option to kill all sub-processes created by the Python process as well as the Python process itself. Didn't find so far.Thymelaeaceous
sys.exit() doesn't kill the process but raise SystemExit Exception which doesn't stop execution by closing the programmRingside
B
80

To stop your program, just press Control + C.

Balzer answered 5/11, 2013 at 4:49 Comment(5)
This method worked on my windows laptop, but on my linux desktop, it showed ^C in the terminal and the system monitor showed python is still using a lot of CPU...Overtop
Is it possible to resume the script after stopping it?Madalena
@Madalena If you want to pause the process and put it in the background, press Ctrl + Z (at least on Linux). Then, if you want to kill it, run kill %n where "n" is the number you got next to "Stopped" when you pressed Ctrl + Z. If you want to resume it, run fg.Molina
Does not work if you have a general except: clause in the program. The except: catches the interrupt, does something (or not), and then the program merrily continues.Molar
@Molar Your general except should have an special except for the error trown by Ctrl+C. Anyway, general excepts are usually discouraged.Marchland
T
69

If your program is running at an interactive console, pressing CTRL + C will raise a KeyboardInterrupt exception on the main thread.

If your Python program doesn't catch it, the KeyboardInterrupt will cause Python to exit. However, an except KeyboardInterrupt: block, or something like a bare except:, will prevent this mechanism from actually stopping the script from running.

Sometimes if KeyboardInterrupt is not working you can send a SIGBREAK signal instead; on Windows, CTRL + Pause/Break may be handled by the interpreter without generating a catchable KeyboardInterrupt exception.

However, these mechanisms mainly only work if the Python interpreter is running and responding to operating system events. If the Python interpreter is not responding for some reason, the most effective way is to terminate the entire operating system process that is running the interpreter. The mechanism for this varies by operating system.

In a Unix-style shell environment, you can press CTRL + Z to suspend whatever process is currently controlling the console. Once you get the shell prompt back, you can use jobs to list suspended jobs, and you can kill the first suspended job with kill %1. (If you want to start it running again, you can continue the job in the foreground by using fg %1; read your shell's manual on job control for more information.)

Alternatively, in a Unix or Unix-like environment, you can find the Python process's PID (process identifier) and kill it by PID. Use something like ps aux | grep python to find which Python processes are running, and then use kill <pid> to send a SIGTERM signal.

The kill command on Unix sends SIGTERM by default, and a Python program can install a signal handler for SIGTERM using the signal module. In theory, any signal handler for SIGTERM should shut down the process gracefully. But sometimes if the process is stuck (for example, blocked in an uninterruptable IO sleep state), a SIGTERM signal has no effect because the process can't even wake up to handle it.

To forcibly kill a process that isn't responding to signals, you need to send the SIGKILL signal, sometimes referred to as kill -9 because 9 is the numeric value of the SIGKILL constant. From the command line, you can use kill -KILL <pid> (or kill -9 <pid> for short) to send a SIGKILL and stop the process running immediately.

On Windows, you don't have the Unix system of process signals, but you can forcibly terminate a running process by using the TerminateProcess function. Interactively, the easiest way to do this is to open Task Manager, find the python.exe process that corresponds to your program, and click the "End Process" button. You can also use the taskkill command for similar purposes.

Tompkins answered 8/11, 2018 at 15:44 Comment(0)
C
62
  • To stop a python script just press Ctrl + C.
  • Inside a script with exit(), you can do it.
  • You can do it in an interactive script with just exit.
  • You can use pkill -f name-of-the-python-script.
Cremate answered 27/6, 2017 at 17:29 Comment(2)
The last option is especially useful when you run the script in a detached mode, e.g. python script.py&Burglarious
@AEM WOW! what a good answer! I searched for a way to kill the python program outside the script and your answer was exactly the answer! Thanks!Upstream
R
61

To stop a python script using the keyboard: Ctrl + C

To stop it using code (This has worked for me on Python 3) :

import os
os._exit(0)

you can also use:

import sys
sys.exit()

or:

exit()

or:

raise SystemExit
Resplendent answered 17/10, 2019 at 7:13 Comment(4)
Thanks. SystemExit is the way to go.Dismast
only os._exit(0) worked for me but for some reason all the others didnt, glad i found os one out, Thank you!Household
raise SystemExit is especially useful if you have never-ending threads (using the multithreading package). The process won't stop if you terminate it using any other method, unless you do ctrl+c twice - but I need an automated restarter :)Shillong
For me also os._exit(0) only worked. ThanksHixson
P
50

To stop a running program, use Ctrl+C to terminate the process.

To handle it programmatically in python, import the sys module and use sys.exit() where you want to terminate the program.

import sys
sys.exit()
Popper answered 25/8, 2018 at 18:33 Comment(1)
This won't work if called from a subprocess.Maricruzmaridel
C
37

Ctrl-Break it is more powerful than Ctrl-C

Constanceconstancia answered 26/10, 2017 at 22:18 Comment(1)
Like Daniel Pryden clarifies in his answer, the Break key on the keyboard could also be labelled Pause, for those who were confused like me. :)Diverticulitis
H
16

When I have a python script running on a linux terminal, CTRL+\ works. (not CRTL + C or D)

Hafner answered 8/11, 2018 at 14:55 Comment(2)
This is far better than Ctrl + Z as that only suspends the processFlagler
Thank you so much - Ubuntu userHight
C
11

Ctrl+Z should do it, if you're caught in the python shell. Keep in mind that instances of the script could continue running in background, so under linux you have to kill the corresponding process.

Cracker answered 20/8, 2018 at 14:20 Comment(1)
this is useful when running (many) parallel processes and CTRL-C just won't kill them all. After CTRL-Z, you may check jobs or ps to then kill 8923754 or whatever jobid/process id you need to killDmitri
R
9

exit() will kill the Kernel if you're in Jupyter Notebook so it's not a good idea. raise command will stop the program.

Ranchero answered 31/12, 2019 at 4:29 Comment(0)
P
7

To stop your program, just press CTRL + D

or exit().

Pied answered 24/7, 2018 at 6:20 Comment(0)
C
6

If you are working with Spyder, use CTRL+. and you will restart the kernel, also you will stop the program.

Carrew answered 8/3, 2019 at 21:11 Comment(1)
FINALLY. A solution that works in Spyder on Windows.Broadbrim
C
5

you can also use the Activity Monitor to stop the py process

Corrigendum answered 6/11, 2015 at 5:48 Comment(0)
A
5

Control+D works for me on Windows 10. Also, putting exit() at the end also works.

Aldenalder answered 31/12, 2018 at 6:40 Comment(0)
W
4

Windows solution: Control + C.

Macbook solution: Control (^) + C.

Another way is to open a terminal, type top, write down the PID of the process that you would like to kill and then type on the terminal: kill -9 <pid>

Woolfell answered 19/5, 2020 at 8:9 Comment(0)
K
4

Try using:

Ctrl + Fn + S

or

Ctrl + Fn + B

Kaleighkalends answered 29/5, 2021 at 12:6 Comment(2)
What exactly these shortcuts do??Kitkitchen
@rhoitjadhav, sometimes in windows a python application doesn't stop by pressing "ctrl+c" only, and a lot of keyboards don't have an explicit "break" key either. So, these shortcuts help you to stop your python application in the terminal if and when required.Kaleighkalends
P
2

Press Ctrl+Alt+Delete and Task Manager will pop up. Find the Python command running, right click on it and and click Stop or Kill.

Progesterone answered 7/10, 2018 at 2:1 Comment(0)
S
1

I might be a little too late to respond but if you're finding it hard to use sys.exit() or exit() and want to kill the python script from within, this might be helpful

import os
import sys
os.system(F"pkill -f {sys.argv[0]}")

Sometimes, in a really long script with many simultaneous threads, it is difficult to kill just with sys.exit but this works like a charm.

Subminiaturize answered 13/6, 2023 at 15:55 Comment(0)
A
0

If you are writing a script to process 349 files, but want to test with fewer, just write a nonexisting word like 'stop' in your list, which will cause a stop in the form of an exception. This avoids dialogs like do you want to kill your process if you use exit() or quit()

Awl answered 4/10, 2022 at 7:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.