如何在Windows上将Ctrl + C发送到子bash进程?

时间:2018-03-14 11:25:25

标签: python bash windows-subsystem-for-linux

环境:

  • Windows 10 1709上的Ubuntu 16.04
  • Python 3.6

考虑这个bash脚本:

#!/usr/bin/env bash

ping localhost

我从Windows命令提示符启动它:

> bash test.sh

当我按下Ctrl + C时,bash会停止并完全退出:

> bash test.sh
PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=128 time=0.156 ms
64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=128 time=0.178 ms
^C
--- localhost ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 0.156/0.167/0.178/0.011 ms

但是,如果我从Python脚本启动它,那么似乎没有办法干净地停止子进程。这是脚本:

#!/usr/bin/env python3

import subprocess
import signal

cmd = ['bash', 'test.sh']
p = subprocess.Popen(cmd)

while p.poll() is None:
    try:
        p.wait(2)
    except subprocess.TimeoutExpired:
        print('{0}: p.send_signal(signal.CTRL_C_EVENT)'.format(p.pid))
        p.send_signal(signal.CTRL_C_EVENT)
    except KeyboardInterrupt as e:
        print(e)
print('{0}: {1}'.format(p.pid, p.returncode))

输出:

> python module1.py
PING localhost (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=128 time=0.193 ms
64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=128 time=0.255 ms
2316: p.send_signal(signal.CTRL_C_EVENT)

2316: 3221225786

如您所见,退出代码为3221225786,即0xC000013ASTATUS_CONTROL_C_EXIT。 此外,ping进程本身并没有退出,而是被杀死了:没有摘要。

有没有什么干净的方法可以阻止Python的WSL bash进程?

0 个答案:

没有答案