使用sys.stdin获取多行输入

Jak*_*rsh 3 python sys

我有以下功能:

def getInput():
    # define buffer (list of lines)
    buffer = []
    run = True
    while run:
        # loop through each line of user input, adding it to buffer
        for line in sys.stdin.readlines():
            if line == 'quit\n':
                run = False
            else:
                buffer.append(line.replace('\n',''))
    # return list of lines
    return buffer
Run Code Online (Sandbox Code Playgroud)

在我的函数takeCommands()中调用,它被调用来实际运行我的程序.

但是,这没有任何作用.我希望将每一行添加到一个数组中,一旦一行=='退出',它就会停止用户输入.我都试过for line in sys.stdin.readlines()for line sys.stdin,但他们都没有注册任何我输入的(我运行它在Windows命令提示符).有任何想法吗?谢谢

Win*_*ong 6

因此,从代码中取出代码并运行一些测试.

import sys
buffer = []
while run:
    line = sys.stdin.readline().rstrip('\n')
    if line == 'quit':
        run = False
    else:
        buffer.append(line)

print buffer
Run Code Online (Sandbox Code Playgroud)

变化:

  • 删除了'for'循环
  • 使用'readline'而不是'readlines'
  • 输入后删除'\n',因此之后的所有处理都更容易.

其他方式:

import sys
buffer = []
while True:
    line = sys.stdin.readline().rstrip('\n')
    if line == 'quit':
        break
    else:
        buffer.append(line)
print buffer
Run Code Online (Sandbox Code Playgroud)

取出'run'变量,因为它不是真正需要的.