在Windows中的Python 2.7中,根据文档,您可以发送CTRL_C_EVENT信号(Python 2.7 Subprocess Popen.send_signal documentation)。但是,当我尝试时,子进程没有收到预期的键盘中断。
以下是父进程的示例代码:
这是子进程的示例代码:
如果我运行parentProcess.py文件,我期望得到"Foo Bar"十次,然后是一个"KeyboardInterrupt",接着是"Foo Bar"四次,但实际上我得到了15次"Foo Bar"。
有没有一种方法让CTRL_C_EVENT像Linux中的SIGINT一样表现为键盘中断?
经过一些阅读,我发现有些信息似乎与Python文档关于CTRL_C_EVENT的描述相矛盾,特别是它说:
“CTRL_C_EVENT 0 生成CTRL+C信号。该信号无法为进程组生成。”
以下网站提供有关创建标志的更多信息: 进程创建标志。
以下是父进程的示例代码:
# 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"十次,然后是一个"KeyboardInterrupt",接着是"Foo Bar"四次,但实际上我得到了15次"Foo Bar"。
有没有一种方法让CTRL_C_EVENT像Linux中的SIGINT一样表现为键盘中断?
经过一些阅读,我发现有些信息似乎与Python文档关于CTRL_C_EVENT的描述相矛盾,特别是它说:
“CTRL_C_EVENT 0 生成CTRL+C信号。该信号无法为进程组生成。”
以下网站提供有关创建标志的更多信息: 进程创建标志。