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.

Leave a Comment