1

I saw this example that launches bash thru subprocess where asynchronous read/write is achieved. However I wonder if there is a way to preserve this behavior and capture a keyboard interrupt.

Run interactive Bash with popen and a dedicated TTY Python

This is my version of the code. The issue is python code is not 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"
Alan Soon
  • 11
  • 2

0 Answers0