How to send EOF to Python sys.stdin from commandli

2019-03-29 14:25发布

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?

4条回答
手持菜刀,她持情操
2楼-- · 2019-03-29 14:47
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()
查看更多
等我变得足够好
3楼-- · 2019-03-29 14:49

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?

查看更多
The star\"
4楼-- · 2019-03-29 14:50

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 sys

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

And I execute it:

$ python a.py

And then enter the following:

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

the program will print:

line 1
line 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.

查看更多
闹够了就滚
5楼-- · 2019-03-29 15:01

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

You can use:

  while 1:
     l = sys.stdin.readline()
查看更多
登录 后发表回答