Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop another already running script in python?

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.

like image 661
Fabulous Job Avatar asked Apr 17 '16 12:04

Fabulous Job


Video Answer


2 Answers

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.

like image 132
mhawke Avatar answered Oct 22 '22 04:10

mhawke


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

like image 32
Padraic Cunningham Avatar answered Oct 22 '22 04:10

Padraic Cunningham