Skip to content
Arvin's Blog

How to stop a console process on Windows using Python

2 min read

Background

  • In Python, we use p = subprocess.Popen(cmd) to start a command and call p.terminate() to stop it. But for some commands on Windows, e.g. ping 127.0.0.1 -n 9999 , terminate it will "force stop" it without producing the "ping statistics" in the end. These processes need to be stopped by the CTRL-C event in order to allow them finish some "cleanups" nicely.

Discusses

Summary

  • Two solutions
    • Solution 1, use subprocess.send_signal(signal.CTRL_C_EVENT) and ignore the KeyboardInterrupt exception at the caller side
      • The key is to handle the side effects of the CTRL-C event, a simple solution is to wait in the caller process until child process exited.
      • example code
        # stop the process
        p.send_signal(signal.CTRL_C_EVENT)
        # wait in the caller process to ignore the KeyboardInterrupt
        try:
        # needs to be longer than the time costs that child process requires to exit
        time.sleep(10)
        except KeyboardInterrupt:
        print("Ignored keyboard interrupt")
      • Cons
        • The CTRL-C event is sent to the whole process group, which means if your python main process starts a lot of processes, e.g. started multiple ping -n 9999 commands, cancel either one will result in all processes (which have the same process group and have not ignored the KeyboardInterrupt exception) exited earlier than expected.
      • In short, this is a solution for simple applications, or applications don't have multiple child processes with the same process group at the same time.
    • Solution 2, use some "Windows hacks"

The final solution

© 2024 by Arvin's Blog. All rights reserved.
Theme by LekoArts