I have got an python script, that is running in the background and that is working with watchdog and os. Is there a way to force quit such a script? I have already tried to press ctrl + x or ctrl + z as proposed in other discussions, what didn't work for me.
2 Answers
If you have sent your process to background with an & at the end of the command line, you can bring it back to the foreground with fg. Once it's back to the foreground, you can kill it with Ctrl+C
test.py:
from time import sleep
n = 0
while True:
sleep(1)
n += 1
print(n)
Example output:
$ python3 -q test.py &
[1] 82675
$ 1
2
3
4
fg
5
6
^CTraceback (most recent call last):
File "test.py", line 6, in <module>
sleep(1)
KeyboardInterrupt
This works from the same shell where you started your script. From another shell, you can find the process ID (PID) with ps, and then kill it with kill -9 <PID>. BTW, the first output line in the above example tells you the PID (82675 in this case).
Assuming you have no other process containing the name of your script in the command line, you could even do this (replacing test.py):
$ kill -9 $(ps | fgrep test.py | fgrep -v fgrep | cut -d' ' -f1)
Comments
If you will run the command jobs
you will see something like this
[1] + suspended python .....
You then can run kill %<job-number>
And you will see:
[1] + 43347 killed vim python ...
fgfollowed byctrl+c?