1

I have a for loop which opens a application with subprocess.Popen and closes it with os.kill.

Whole code:

import subprocess
import time
import signal
import os

with open('programs.txt') as f:
    programs = f.readlines()

programs = [x.strip() for x in programs] 

for program in programs: 
    programOpened = subprocess.Popen([r"C:\\path\\to\\application\\" + program])
    time.sleep(5)

    os.kill(programOpened.pid, signal.CTRL_C_EVENT)

This throws for my this exception:

os.kill(programOpened.pid, signal.CTRL_C_EVENT) 
SystemError: <built-in function kill> returned a result with an error set

Why is this exception thrown and how could i close a subprocess in a for loop?

Nightscape
  • 464
  • 6
  • 19
  • 1
    why not just `programOpened.terminate()` ? – Jean-François Fabre Sep 23 '18 at 21:40
  • @Jean-FrançoisFabre, presumably the application has a Ctrl+C handler that tries to exit gracefully. `terminate()` forcefully kills the process, akin to a Unix `SIGKILL`. – Eryk Sun Sep 24 '18 at 00:35
  • Note that the upvoted answer on the linked question is misleading and wrong on several points. I'll edit it later if I have time and remember to do so. This particular error is a bug in `os.kill`, which even without bugs is one of the most poorly thought out functions in Windows CPython. It should have been split into `os.killpg` and `os.kill`, based on `GenerateConsolCtrlEvent` and `TerminateProcess`, respectively. – Eryk Sun Sep 24 '18 at 00:38
  • @eryksun yeah, that's what I thought afterwards. I hope you agree with the duplicate. – Jean-François Fabre Sep 24 '18 at 08:18
  • @Jean-François Fabre I thought your answer was good, it helped my. – Nightscape Sep 24 '18 at 08:19
  • you mean the duplicate link? it's a duplicate either way. Glad I could help. – Jean-François Fabre Sep 24 '18 at 08:21
  • no I meant your answer, the duplicate link is way to specific for my question. – Nightscape Sep 24 '18 at 08:22
  • Okay, well... all good then :) added another dupe linik for good measure – Jean-François Fabre Sep 24 '18 at 08:27

0 Answers0