1

I'm trying to run a python script that runs, with subprocess.popen (), one or more instances of another python script. At some point I need to finish them gently. These scripts execute a while loop and when ctrl-c is catched they execute a clean-up routine and terminate.

At the beginnig my idea was to send ctrl-c to those scripts with subproc.send_signal() but it doesn't work. I tryed to use subproc.terminate() or os.kill(os.kill(subproc.pid, signal.CTRL_C_EVENT)) and other solution founded on Internet but nothing works well.

How can I gently terminate my scripts? Is the way I run my scripts right? Here is my code:

processes = []
    for i in range(0, capsules_number):
        p = subprocess.Popen(["python.exe ", "Capsula.py ", str(i)])
        processes.append(p)

    input("Press any key to terminate programs")

    for p in processes:
        # Terminate process
        processes.remove(p)

   
Denis
  • 49
  • 6
  • ctrl+c sends a `signal.SIGINT` signal to the process, so did you think about sending those ? – Ahmed AEK Jan 16 '22 at 20:00
  • Does this answer your question? [Sending ^C to Python subprocess objects on Windows](https://stackoverflow.com/questions/7085604/sending-c-to-python-subprocess-objects-on-windows) – Bharel Jan 16 '22 at 20:05
  • Yes I already tried all your suggestions but it doesn't work... – Denis Jan 16 '22 at 20:33

1 Answers1

1

From the subprocess documentation:

CTRL_C_EVENT and CTRL_BREAK_EVENT can be sent to processes started with a creationflags parameter which includes CREATE_NEW_PROCESS_GROUP.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
  • Thanks! can you tell me something more? I don't know what process group are... – Denis Jan 16 '22 at 20:50
  • This answer [doesn't actually work](https://learn.microsoft.com/en-us/windows/console/generateconsolectrlevent?redirectedfrom=MSDN). Read the duplicate. – Bharel Jan 16 '22 at 21:30