Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send EOF to Python sys.stdin from commandline? CTRL-D doesn't work

I am writing to my Python process from the commandline on unix. I want to send EOF (or somehow flush the stdin buffer, so Python can read my input.)

If I hit CTRL-C, I get a KeyboardError.

If I hit CTRL-D, the program just stops.

How do I flush the stdin buffer?

like image 248
Joseph Turian Avatar asked Dec 12 '09 03:12

Joseph Turian


2 Answers

Control-D should NOT make your program "just stop" -- it should close standard input, and if your program deals with that properly, it may perfectly well continue if it needs to!

For example, given the following st.py:

import sys

def main():
  inwas = []
  for line in sys.stdin:
    inwas.append(line)
  print "%d lines" % len(inwas),
  print "initials:", ''.join(x[0] for x in inwas)

if __name__ == '__main__':
  main()

we could see something like

$ python st.py
nel mezzo del cammin di nostra vita
mi ritrovai per una selva oscura
che la diritta via era smarrita
3 lines initials: nmc
$ 

if the control-D is hit right after the enter on the third line -- the program realizes that standard input is done, and performs the needed post-processing, all neat and proper.

If your program prematurely exits on control-D, it must be badly coded -- what about editing you question to add the smallest "misbehaving" program you can conceive of, so we can show you exactly HOW you're going wrong?

like image 174
Alex Martelli Avatar answered Oct 06 '22 00:10

Alex Martelli


If you use 'for l in sys.stdin', it is buffered.

You can use:

  while 1:
     l = sys.stdin.readline()
like image 20
Joseph Turian Avatar answered Oct 05 '22 22:10

Joseph Turian