Python在Windows上发送SIGINT信号子进程

时间:2018-06-15 14:45:11

标签: python python-3.x subprocess sigint

我已经在stackoverflow上提出了很多问题,但它们太旧了,对我没用。 我有一个子进程,并希望发送CTRL_C_EVENT信号来阻止它。我不想直接杀死它。 这是我的代码:

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)

此处例外:

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

1 个答案:

答案 0 :(得分:0)

我希望这是因为for line in process.stdout:

,您的流程仍在使用中

您可能必须首先退出for循环然后发送 CTRL_C_EVENT信号以停止

尝试类似的东西:

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)