Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last line of stdin not being read when EOF is detected

Tags:

python

stdin

Probably an easy question, but I am basically trying to replicate the behavior (very sparsely and simplistically) of the cat command but in python. I want the user to be able to enter all the text they wish, then when they enter an EOF (by pressing ctrl+d or cmd+d) the program should print out everything they enter.

import sys
for line in sys.stdin:
    print line

If I enter the input lines and follow the last line with a return character, and then press cmd+d:

never gonna give you up
never gonna let you down
never gonna run around
and desert you

then the output is

never gonna give you up
never gonna let you down
never gonna run around
and desert you

However, if I press cmd+d while I am still on the last line "and desert you" then the output is:

never gonna give you up
never gonna let you down
never gonna run around

How can I modify the program such that if the user presses the EOF on the last line, then it should still be included as part of the output?

like image 229
Jeremy Fisher Avatar asked Oct 20 '25 01:10

Jeremy Fisher


1 Answers

The behavior of Control-D is actually a function of the TTY driver of the operating system, not of Python. The TTY driver normally sends data to programs a full line at a time. You'll note that 'cat' and most other programs behave the same way.

To do what you're asking is non-trivial. It usually requires putting the TTY into raw mode, reading and processing data (you would get the Control-D character itself), and then taking it out of raw mode before exiting (you don't want to exit in raw mode!)

Procedures for doing that are O/S dependent, but you might be able to make use of tty.setraw() and tty.setcbreak().

like image 191
Curt Avatar answered Oct 22 '25 15:10

Curt