Skip to content
Advertisement

Run interactive Bash in dumb terminal using Python subprocess.Popen and pty

This question is similar to Run interactive Bash with popen and a dedicated TTY Python, except that I want to run Bash in a “dumb” terminal (TERM=dumb), and without putting the tty into raw mode.

The code below is my attempt. The code is similar to the solution given in the linked question, with the major difference that it does not put the tty into raw mode, and sets TERM=dumb.

JavaScript

There are two problems with the code above:

  • The code will re-echo whatever the user inputs. For example, if the user inputs printf '', the code above will print printf '' on the next line before printing the next bash prompt.
  • Ctrlc and Ctrld do not behave as one would expect in bash.

How should I fix these problems?

Advertisement

Answer

That’s exactly the side effects of not putting the tty in raw mode. Usually a program (like ) which handles pty would put the outer tty in raw mode.

  • Your Python script’s tty (or pty) echos what you input and the new pty echos for the 2nd time. You can disable ECHO on the new pty. For example:

    JavaScript
  • Your Python script’s tty is not in raw mode so when you press ctrl-d Python would not get the literal ctrl-d ('04'). Instead, Python would reach EOF and read() returns an empty string. So to make the spawned shell exit you can

    JavaScript
  • Similarly, the Python’s tty is not in raw mode so when you press ctrl-c, it’ll not get the literal ctrl-c ('03'). Instead it’s killed. As a workaround you can catch SIGINT.

    JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement