I have readed so many questions on stackoverflow but they are too old and not helpful for me. I have a subprocess and want to send CTRL_C_EVENT Signal to stop it. I don't want to kill it directly. Here is my code :
import subprocess
import os
import signal
CREATE_NO_WINDOW = 0x08000000
'''
I tried these too but i failed.
creationflags=CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
CREATE_NEW_PROCESS_GROUP = 0x00000200
DETACHED_PROCESS = 0x00000008
'''
cmd = 'my cmd arguments'
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,universal_newlines=True,shell=True,creationflags=CREATE_NO_WINDOW)
test = 0
for line in process.stdout:
test += 1
if (test > 60):
os.kill(process.pid, signal.CTRL_C_EVENT)
#This fails too
#process.send_signal(signal.CTRL_C_EVENT)
else:
print(line)
Here exception :
OSError: [WinError 6] The handler is invalid
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\xxxxxxx\Desktop\xxxxx\test subprocess.py", line 16, in <module>
os.kill(process.pid, signal.CTRL_C_EVENT)
SystemError: <built-in function kill> returned a result with an error set
I expect that is because your process is still in use due to the for line in process.stdout:
You may have to exit the for loop first, then send CTRL_C_EVENT Signal to stop it
Try something like that:
import subprocess
import os
import signal
CREATE_NO_WINDOW = 0x08000000
'''
I tried these too but i failed.
creationflags=CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
CREATE_NEW_PROCESS_GROUP = 0x00000200
DETACHED_PROCESS = 0x00000008
'''
cmd = 'my cmd arguments'
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,universal_newlines=True,shell=True,creationflags=CREATE_NO_WINDOW)
test = 0
CTRL_C_EVENT_is_required=False
for line in process.stdout:
test += 1
if (test > 60):
CTRL_C_EVENT_is_required=True
break
else:
print(line)
if CTRL_C_EVENT_is_required==True:
os.kill(process.pid, signal.CTRL_C_EVENT)
User contributions licensed under CC BY-SA 3.0