在Windows中使用子程序Popen.send_signal(CTRL_C_EVENT)时如何实现预期的结果?

Windows 2.7的Python文档中,您可以发送一个CTRL_C_EVENT (Python 2.7subprocessPopen.send_signal文档)。 但是,当我尝试它,我没有收到预期的subprocess中的键盘中断。

这是父进程的示例代码:

# 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我希望得到“富酒吧”十倍,然后一个“KeyboardInterrupt”,其次是“富酒吧”4倍,但我得到了“富酒吧”15倍。

有没有办法让CTRL_C_EVENT的行为像键盘中断,就像SIGINT在Linux中的行为一样?

在做了一些阅读之后,我发现一些信息似乎与关于CTRL_C_EVENT的python文档相矛盾,特别是它说

CTRL_C_EVENT 0生成一个CTRL + C信号。 这个信号不能为过程组生成

以下站点提供有关创build标志的更多信息: stream程创build标志。

Solutions Collecting From Web of "在Windows中使用子程序Popen.send_signal(CTRL_C_EVENT)时如何实现预期的结果?"

子进程信号处理的这种方法在Linux和Windows 2008上都适用,都使用Python 2.7.2,但它使用Ctrl-Break而不是Ctrl-C。 请参阅http://msdn.microsoft.com/en-us/library/ms683155%28v=vs.85%29.aspx中有关进程组和Ctrl-C的注释&#x3002;

catcher.py:

 import os import signal import sys import time def signal_handler(signal, frame): print 'catcher: signal %d received!' % signal raise Exception('catcher: i am done') if hasattr(os.sys, 'winver'): signal.signal(signal.SIGBREAK, signal_handler) else: signal.signal(signal.SIGTERM, signal_handler) print 'catcher: started' try: while(True): print 'catcher: sleeping...' time.sleep(1) except Exception as ex: print ex sys.exit(0) 

thrower.py:

 import signal import subprocess import time import os args = [ 'python', 'catcher.py', ] print 'thrower: starting catcher' if hasattr(os.sys, 'winver'): process = subprocess.Popen(args, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) else: process = subprocess.Popen(args) print 'thrower: waiting a couple of seconds for catcher to start...' time.sleep(2) print 'thrower: sending signal to catch' if hasattr(os.sys, 'winver'): os.kill(process.pid, signal.CTRL_BREAK_EVENT) else: process.send_signal(signal.SIGTERM) print 'thrower: i am done' 

尝试

 win32api.GenerateConsoleCtrlEvent(CTRL_C_EVENT, pgroupid) 

要么

 win32api.GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, pgroupid) 

引用:

http://docs.activestate.com/activepython/2.5/pywin3/win32process_CREATE_NEW_PROCESS_GROUP.html

http://msdn.microsoft.com/en-us/library/ms683155%28v=vs.85%29.aspx

阅读有关dwProcessGroupId的信息,groupid应该与进程ID相同