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

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


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 sysdef 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.pynel mezzo del cammin di nostra vitami ritrovai per una selva oscurache la diritta via era smarrita3 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?


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

You can use:

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


I think I know what's happening. You are hitting ctrl-D without hitting enter. If you want to send a line to the program, just hit enter. If you hit ctrl-D without hitting enter, you can hit ctrl-D again and your program should see the line then. In this case (two ctrl-Ds in succession), your program will not see a newline at the end of the line.

For example, let's say I have a Python script a.py:

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

And I execute it:

$ python a.py

And then enter the following:

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

the program will print:

line 1line 2$

$ is the shell-prompt. Here's a full session with the above input:

$ python a.py
line 1
line 2 line1
line 2$

(Bold show the program's output. Roman-case is for showing what I typed, sans the two ctrl-Ds)

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