Home > OS >  Run subprocess in thread and stop it
Run subprocess in thread and stop it

Time:09-23

I am trying to run a python file with another python file in threading with subprocess. I am able to run the file, but not able to stop it.

What I want is

I want to run the test.py with my main.py in thread and stop it by entering stop in the console.

test.py

import time

while True:
    print("Hello from test.py")
    time.sleep(5)

main.py

import subprocess
import _thread

processes = []

def add_process(file_name):
    p = subprocess.Popen(["python", file_name], shell=True)
    processes.append(p)
    print("Waiting the process...")
    p.wait()

while True:
    try:
        # user input
        ui = input("> ")

        if ui == "start":
            _thread.start_new_thread(add_process, ("test.py",))
            print("Process started.")
        elif ui == "stop":
            if len(processes) > 0:
                processes[-1].kill()
                print("Process killed.")
        else:
            pass
    except KeyboardInterrupt:
        print("Exiting Program!")
        break

Output

C:\users\me>python main2.py
> start
Process started.
> Waiting the process...
Hello from test.py, after 0 seconds
Hello from test.py, after 4 seconds

> stop
Process killed.
> Hello from test.py, after 8 seconds
Hello from test.py, after 12 seconds
    
> stopHello from test.py, after 16 seconds

Process killed.
> Hello from test.py, after 20 seconds

>

The program is still running even after I stop it with kill function, I have tried terminate also. I need to stop that, how can I. Or, is there any alternative module for subprocess to do this?

CodePudding user response:

I suspect you have just started multiple processes. What happens if you replace your stop code with this:

for proc in processes:
    proc.kill()

This should kill them all.

Note that you are on windows, and on windows terminate() is an alias for kill(). It is not a good idea to rely on killing processes gracelessly anyway, and if you need to stop your test.py you would be better off having some means of communicating with it and having it exit gracefully.

Incidentally, you don't want shell=True, and you're better off with threading than with _thread.

  • Related