2

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.

Mohd Ali
  • 311
  • 2
  • 13
  • what @J.F, Sebastian suggested is also better approach if you do not want to spend too much time thinking however if you want to learn something new and stick to command prompt, try curses https://docs.python.org/2/howto/curses.html and here is somewhat similar answer to what you are looking for : http://stackoverflow.com/questions/21784625/how-to-input-a-word-in-ncurses-screen another great package I found is npyscreen https://code.google.com/p/npyscreen/ – Ciasto piekarz Feb 28 '15 at 14:34

3 Answers3

5

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

Example

12 22 -23 13 -12 23 -1 23 12

Output

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. Split input into space-separated tokens
  2. Get tokens until -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())))

Output

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

Maybe msvcrt will help you

import msvcrt
print 'Press a to continue:\n'
inPchar = msvcrt.getch()
if inPchar.upper() == 'A': 
   print 'Pressed A'
Aleksander Monk
  • 2,787
  • 2
  • 18
  • 31
  • this will make user not able add any word that has a in it. – Ciasto piekarz Feb 28 '15 at 13:02
  • @san of course, but "A" is just an example He wants to stop reading input after user type something. So he can change "A" to any other symbol which 100% won't be in this input and it will solve this problem. – Aleksander Monk Feb 28 '15 at 13:10
  • even then its not perfect solution, as user may end up entering any type of input and moreover msvcrt is neither available for all platforms nor a user may already have it on windows unless its a part of standard library. – Ciasto piekarz Feb 28 '15 at 13:54
0

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

Joe Young
  • 5,749
  • 3
  • 28
  • 27
  • I have tried that but what happens if 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. – Mohd Ali Feb 28 '15 at 11:30
  • @malee I modified my answer to handle repeating -1 separators. – Joe Young Feb 28 '15 at 11:37