在windows的Python2.7中,根据文档,您可以发送一个CTRL_C_事件
(Python 2.7 Subprocess Popen.send_signal documentation).
但是,当我尝试时,在子进程中没有收到预期的键盘中断。
这是父进程的示例代码:# FILE : parentProcess.py
import subprocess
import time
import signal
CREATE_NEW_PROCESS_GROUP = 512
process = subprocess.Popen(['python', '-u', 'childProcess.py'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
creationflags=CREATE_NEW_PROCESS_GROUP)
print "pid = ", process.pid
index = 0
maxLoops = 15
while index < maxLoops:
index += 1
# Send one message every 0.5 seconds
time.sleep(0.5)
# Send data to the subprocess
process.stdin.write('Bar\n')
# Read data from the subprocess
temp = process.stdout.readline()
print temp,
if (index == 10):
# Send keyboard Interrupt
process.send_signal(signal.CTRL_C_EVENT)
这是子进程的示例代码:# FILE : childProcess.py
import sys
while True:
try:
# Get data from main process
temp = sys.stdin.readline()
# Write data out
print 'Foo ' + temp,
except KeyboardInterrupt:
print "KeyboardInterrupt"
如果我运行parentProcess.py文件,我希望得到“Foo Bar”10次,然后是“KeyboardInterrupt”4次,然后是“Foo Bar”15次。
有没有办法让CTRL_C_事件表现为键盘中断,就像SIGINT在Linux中一样?
在做了一些阅读之后,我发现一些信息似乎与关于CTRL_C_事件的python文档相反,特别是它说CTRL_C_EVENT
0 Generates a CTRL+C signal. This signal cannot be generated for process groups