Environment:
Consider this bash script:
#!/usr/bin/env bash
ping localhost
I start it from Windows command prompt:
> bash test.sh
When I press Ctrl+C, bash stops and exits cleanly:
> 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
However, if I start it from Python script, then it seems that there is no way to stop the child process cleanly. Here is the script:
#!/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))
Output:
> 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
As you can see, the exit code is 3221225786
, aka 0xC000013A
or STATUS_CONTROL_C_EXIT
.
Also, ping process didn't exit by itself, but was rather killed: no summary.
Is there any clean way to stop WSL bash process from Python?
User contributions licensed under CC BY-SA 3.0