5

There is a way to start another script in python by doing this:

import os

os.system("python [name of script].py")

So how can i stop another already running script? I would like to stop the script by using the name.

Fabulous Job
  • 150
  • 2
  • 2
  • 10

3 Answers3

6

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.

mhawke
  • 84,695
  • 9
  • 117
  • 138
5

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

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • 1
    Hi @Padraic Cunningham, your script worked well for me. However, when I tried to tweak it a bit (replaced sys.argv[1] with the path to my script --> 'home/pi/MotionDetector.py') it threw an error :" CalledProcessError: Command '['pkill', '-9', '-f', '/home/pi/MotionDetector.py']' returned non-zero exit status 1" Can you pls help? – Json Sep 19 '18 at 17:20
0

Just put in the name of the program NOT the path to your script. so it would be

check_call(["pkill", "-f", "MotionDetector.py"])
Buteman
  • 53
  • 8