If I use raw_input() it takes all the user input. I want to stop taking input just when user enters '-1'.
What I mean is if user enters '12 22 -23 3 -1 23 -1 23', it should not read after 3.
Any other way of reading input will also do.
If I use raw_input() it takes all the user input. I want to stop taking input just when user enters '-1'.
What I mean is if user enters '12 22 -23 3 -1 23 -1 23', it should not read after 3.
Any other way of reading input will also do.
... The sequence never stops. Example: 1 2 -1 2 -3 -1 34 12 ...................... it never stops. But I have to stop reading if I encounter -1.
raw_input()
always reads the full line.
If you don't want to read the full line; you could try sys.stdin.read(1)
instead:
import sys
def read_until_minus_one():
buf = []
seen_minus = False
while True:
char = sys.stdin.read(1)
if not char: # EOF
break
if char == '1' and seen_minus:
buf.pop() # chop the last minus
break # seen -1
else:
seen_minus = (char == '-')
buf.append(char)
return ''.join(buf)
print(read_until_minus_one())
12 22 -23 13 -12 23 -1 23 12
12 22 -23 13
Note: it stops as soon as -1
is read. The subsequent sys.stdin.read(1)
returns '2'
in this case.
If you want to stop only if -1
is encountered as a space-separated token (not as a part of a number as in -12
) then the input parsing could be split on two stages:
-1
is encountered#!/usr/bin/env python
import sys
from functools import partial
from itertools import takewhile
def get_tokens(stream=sys.stdin):
token = []
for char in iter(partial(stream.read, 1), ''):
if char.isspace(): # use any space as a separator
if token:
yield ''.join(token)
del token[:]
else:
token.append(char)
if token:
yield ''.join(token)
print(' '.join(takewhile(lambda s: s != '-1', get_tokens())))
12 22 -23 13 -12 23
Notice: it read more content in this case because -1
is not recognized inside -12
in this case.
Note: you don't need curses
or other means of reading a single character from the user in this case. You only need it if the input is interactive and you want to get the content sooner than the user presses Enter (or EOF).
sys.stdin
is buffered by default. Therefore .read(1)
may read more than one character internally. If we are the only consumer of the stream (likely) then it doesn't matter because from our end .read(1)
always returns one character at a time.
Maybe msvcrt will help you
import msvcrt
print 'Press a to continue:\n'
inPchar = msvcrt.getch()
if inPchar.upper() == 'A':
print 'Pressed A'
You can split the string on -1. It'll create a list and you only use the first element of the list:
full_input = raw_input('Enter sequence:')
user_input = full_input.split('-1')
print user_input[0].strip()
The output:
macbook:Downloads joeyoung$ python splitinput.py
Enter sequence:1 2 -1 2 -3 -1 34 12
1 2
EDIT: I modified my solution above to handle repeats of the -1 separator