Reputation: 115
Im using lexer.input(sys.stdin.read())
to be able to write in console with freedom and to tokenize if´s, for´s etc in lexer ,but I want that when someone write "exit" it send CTRL+D so sys.stdin.read() stop reading and end my program .
Tried to do this in my code:
lexer.input(sys.stdin.read())
for tok in lexer:
if tok.value == "exit":
sys.stdin.read(0o4)
But it didnt exit. The 004 is because in this page https://mail.python.org/pipermail/python-list/2002-July/165325.html they say what is the code for CTRL+D but it doesnt say how to send it.
Upvotes: 0
Views: 435
Reputation: 241671
sys.stdin.read()
will read all of stdin before returning, so the input function in
lexer.input(sys.stdin.read())
cannot be prematurely terminated by anything done inside the lexer. The entire input has been read before lexer.input
has even been called.
You can read up to (but not including) the first line containing exit
with the following:
from itertools import takewhile
lexer.input(''.join(takewhile(lambda line: 'exit' not in line, sys.stdin)))
although I'd personally prefer something like
from itertools import takewhile
notdone = lambda line: not line.lstrip().startswith('exit')
lexer.input(''.join(takewhile(notdone, sys.stdin)
That won't get confused by lines which happen to contain exit
in the middle of something, but will still stop if it hits a line whose first word just starts with exit
. (Fortunately, the only such words in standard English are simple variations on the word exit
itself.)
Upvotes: 2