How to stop another already running script in python?
It is more usual to import the other script and then invoke its functions and methods.
If that does not work for you, e.g. the other script is not written in such a way that is conducive to being imported, then you can use the subprocess
module to start another process.
import subprocess
p = subprocess.Popen(['python', 'script.py', 'arg1', 'arg2'])
# continue with your code then terminate the child
p.terminate()
There are many possible ways to control and interact with the child process, e.g. you can can capture its stdout and sterr, and send it input. See the Popen()
documentation.
If you start the script as per mhawkes suggestion is it a better option but to answer your question of how to kill an already started script by name you can use pkill and subprocess.check_call:
from subprocess import check_call
import sys
script = sys.argv[1]
check_call(["pkill", "-9", "-f", script])
Just pass the name to kill:
padraic@home:~$ cat kill.py
from subprocess import check_call
import sys
script = sys.argv[1]
check_call(["pkill", "-9", "-f", script])
padraic@home:~$ cat test.py
from time import sleep
while True:
sleep(1)
padraic@home:~$ python test.py &
[60] 23361
padraic@home:~$ python kill.py test.py
[60] Killed python test.py
Killed
That kills the process with a SIGKIll
, if you want to terminate remove the -9:
padraic@home:~$ cat kill.py
from subprocess import check_call
import sys
script = sys.argv[1]
check_call(["pkill", "-f", script])
padraic@home:~$ python test.py &
[61] 24062
padraic@home:~$ python kill.py test.py
[61] Terminated python test.py
Terminated
That will send a SIGTERM
. Termination-Signals