How to send EOF to Python sys.stdin from the command line? CTRL-D is not working

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

If I press CTRL-C, I will get KeyboardError.

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

How to flush stdin buffer?

+5
source share
4 answers

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

You can use:

  while 1:
     l = sys.stdin.readline()
+1
source

Control-D " " - ​​ , , , !

, 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()

-

$ 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
$ 

-D - , , -, .

Control-D, - , , " ", ,

+11

, , . ctrl-D, enter. , enter. ctrl-D, enter, ctrl-D, . ( ctrl-D ) .

, , Python script a.py:

import sys

for line in sys.stdin:
    sys.stdout.write('%s' % line)

:

$ python a.py

:

line 1
line 2<ctrl-D><ctrl-D>

:

line 1
line 2$

$ - . :

$python a.py
1
2 line1
2 $

( Bold shows the output of the program. Roman-case is intended to display what I typed, without two ctrl-Ds)

If this is not what is happening, you need to tell us more about what you are doing.

+2
source
try:
    # You might be inside the while-loop
    foo = raw_input('Spam: ') # Or whatever...
except EOFError:
    print 'And now for something completely different.'
    sys.exit()
+1
source

All Articles