我看到这个例子通过子进程启动bash,实现了异步读/写。但是我想知道是否有办法保留这种行为并捕获键盘中断。
Run interactive Bash with popen and a dedicated TTY Python
这是我的代码版本。问题是python代码不是INTERRUPTED。
import subprocess
import sys
import os
import signal
import atexit
import select
import termios
import tty
import pty
def execute(command):
old_tty = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin.fileno())
master_fd, slave_fd = pty.openpty()
process = subprocess.Popen(command,
preexec_fn=os.setsid,
stdin=slave_fd,
stdout=slave_fd,
stderr=slave_fd,
universal_newlines=True)
global child_pid
child_pid = process.pid
while process.poll() is None:
r, w, e = select.select([sys.stdin, master_fd], [], [])
if sys.stdin in r:
d = os.read(sys.stdin.fileno(), 10240)
os.write(master_fd, d)
elif master_fd in r:
o = os.read(master_fd, 10240)
if o:
os.write(sys.stdout.fileno(), o)
output = process.communicate()[0]
exitCode = process.returncode
if (exitCode == 0):
return output
else:
raise ProcessException(command, exitCode, output)
def exit_protocol():
global child_pid
if child_pid is None:
pass
else:
print "Shutting Down bash", child_pid
atexit.register(exit_protocol)
try:
execute('bash')
except KeyboardInterrupt as exc:
print "Clean up all bash's child jobs"