How to stop another already running script in python?

不想你离开。 提交于 2019-11-28 10:36:34

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

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

check_call(["pkill", "-f", "MotionDetector.py"])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!