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

自闭症网瘾萝莉.ら 提交于 2019-12-21 17:22:21

问题


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?


回答1:


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?




回答2:


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

You can use:

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



回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/1892215/how-to-send-eof-to-python-sys-stdin-from-commandline-ctrl-d-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!