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?
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?
If you use 'for l in sys.stdin', it is buffered.
You can use:
while 1:
l = sys.stdin.readline()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With