Python Forum
When is stdin not connected to a tty, but can still be used interactively?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
When is stdin not connected to a tty, but can still be used interactively?
#1
I'm looking at some code which is intended to be used interactively, and I don't quite understand it.

Simplified, the code looks like this:

import sys

def example():
    try:
        import tty
        fd = sys.stdin.fileno()
        old = tty.tcgetattr(fd)
        tty.setcbreak(fd)
        getchar = lambda: sys.stdin.read(1)
    except (ImportError, AttributeError, io.UnsupportedOperation):
        # Fallback for when the terminal is not a tty.
        tty = None
        getchar = lambda: sys.stdin.readline()[:-1][:1]
    try:
        while True:
            c = getchar()
            if c in ('q', 'Q'):
                break
    finally:
        if tty:
            tty.tcsetattr(fd, tty.TCSAFLUSH, old)
The code waits until the user types 'q' or 'Q'. What I don't get is under what circumstances can you have a terminal session, complete with stdin, but *not* be attached to a tty?

Can somebody explain the circumstances where the fallback code will run please?

Thanks in advance.
Reply
#2
The program does not say that you have a terminal session when you are not attached to a tty. When it is not attached to a tty, it simply reads the standard input line by line and it takes the first character of each line as if the user had typed it in a terminal.

This allows automating input by the means of a pipe for example
Output:
$ simulate_keystrokes | python program.py
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to check if Skype call is connected or disconnected in Python? boral 1 408 Dec-28-2023, 08:31 AM
Last Post: buran
  STDIN not working H84Gabor 3 3,598 Sep-06-2021, 08:10 AM
Last Post: H84Gabor
  Printing to a printer connected to pi 4 alan 2 2,457 Oct-04-2020, 10:08 PM
Last Post: alan
  How to read a file using stdin? pyth0nus3r 1 2,850 Aug-24-2019, 01:14 AM
Last Post: Larz60+
  What is the sys.stdin.isatty() command? pyth0nus3r 2 11,474 Aug-22-2019, 04:37 PM
Last Post: pyth0nus3r
  getting error "exec_proc.stdin.write(b'yes\n') IOError: [Errno 32] Broken pipe" Birju_Barot 0 2,947 Jul-23-2019, 11:50 AM
Last Post: Birju_Barot
  is it safe to close stdin Skaperen 1 2,683 Apr-04-2019, 06:57 AM
Last Post: Gribouillis
  Need help with reading input from stdin into array list Annie123 2 5,083 Mar-24-2019, 01:19 PM
Last Post: Annie123
  How to detect wireless modem connected serially to my laptop in python barry76 3 3,560 Jan-08-2019, 06:18 AM
Last Post: Gribouillis
  Arduino Uno connected to PI 0 W - Sensor Data MQTT runboy 4 3,081 Nov-07-2018, 03:55 AM
Last Post: runboy

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020