简体   繁体   English

如何在Python中使用raw_input()在某个字符后停止从用户读取输入?

[英]How to stop reading input from user after a certain char using raw_input() in Python?

If I use raw_input() it takes all the user input. 如果我使用raw_input(),它将接受所有用户输入。 I want to stop taking input just when user enters '-1'. 我只想在用户输入“ -1”时停止输入。

What I mean is if user enters '12 22 -23 3 -1 23 -1 23', it should not read after 3. 我的意思是,如果用户输入“ 12 22 -23 3 -1 23 -1 23”,则在输入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. 示例:1 2 -1 2 -3 -1 34 12 ...............................永不停止。 But I have to stop reading if I encounter -1. 但是如果遇到-1,我必须停止阅读。

raw_input() always reads the full line. raw_input()始终读取整行。

If you don't want to read the full line; 如果您不想阅读全文 you could try sys.stdin.read(1) instead: 您可以尝试使用sys.stdin.read(1)代替:

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. 注意:读取-1它将停止。 The subsequent sys.stdin.read(1) returns '2' in this case. 在这种情况下,后续的sys.stdin.read(1)返回'2'


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作为以空格分隔的标记(而不是像-12那样作为数字的一部分)时才想停止,则可以将输入解析分为两个阶段:

  1. Split input into space-separated tokens 将输入拆分为以空格分隔的令牌
  2. Get tokens until -1 is encountered 获取令牌,直到遇到-1
#!/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. 注意:在这种情况下,它会读取更多内容,因为在这种情况下-12内部无法识别-1


Note: you don't need curses or other means of reading a single character from the user in this case . 注意: 在这种情况下,您不需要使用curses其他方式从用户读取单个字符 You only need it if the input is interactive and you want to get the content sooner than the user presses Enter (or EOF). 仅当输入是交互式的并且要比用户按Enter (或EOF)更早地获取内容时才需要它。

sys.stdin is buffered by default. sys.stdin默认情况下被缓冲。 Therefore .read(1) may read more than one character internally. 因此, .read(1)可能在内部读取多个字符。 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. 如果我们(可能)是流的唯一使用者,则没关系,因为从我们的末端开始, .read(1)始终一次返回一个字符。

You can split the string on -1. 您可以在-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 编辑:我修改了上面的解决方案来处理-1分隔符的重复

Maybe msvcrt will help you 也许msvcrt会帮助您

import msvcrt
print 'Press a to continue:\n'
inPchar = msvcrt.getch()
if inPchar.upper() == 'A': 
   print 'Pressed A'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM