如何读取多行原始输入?

87
我想创建一个Python程序,接受多行用户输入。例如:
This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.

我该如何输入多行原始输入?


4
如果你正在输入多行内容,如何确定输入何时结束? - Blckknght
1
编写一个循环,使用raw_input获取用户输入,直到用户输入“done”或其他内容。 - Pramod
1
我猜你的目标是获取用户输入,但你可以在提示符中添加换行符\n,例如:raw_input('foo\nbar: ')。 - Hedde van der Heide
1
@felix001,你只需要raw_input的解决方案还是直接从stdin获取输入也可以? - jamylak
你可以尝试这个链接:http://www.daniweb.com/software-development/python/threads/269208/raw_input-and-multiple-lines - Jacob George
17个回答

117
sentinel = '' # ends when this string is seen
for line in iter(input, sentinel):
    pass # do things here

为了将每一行作为字符串获取,你可以这样做:
'\n'.join(iter(input, sentinel))

Python 2:

'\n'.join(iter(raw_input, sentinel))

15
我已经成为Python爱好者约有6年了,但我从未听说过iter()的这种其他形式。您真是一个天才! - inspectorG4dget
7
我该如何将EOF设置为哨兵字符? - MadTux
2
@Randy 你可以这样做,只是看起来不太美观:iter(lambda: raw_input('prompt'), sentinel) - jamylak
2
请注意,在Python 3中,raw_input现在是input - wecsam
3
@wecsam现在已经添加了这一内容,以使答案适用于所有Python版本。 - jamylak
显示剩余6条评论

20

或者你可以尝试使用sys.stdin.read(),它会返回整个输入直到出现EOF

import sys
s = sys.stdin.read()
print(s)

4
如果您需要处理包含多个空行或其他任何数据的文本,这个解决方案非常完美。它会在遇到EOF(Ctrl+D;在Windows上是Ctrl+Z)时停止。 - Marko

8

当用户输入空行(或更改stopword为其他内容)时,继续读取行。

text = ""
stopword = ""
while True:
    line = raw_input()
    if line.strip() == stopword:
        break
    text += "%s\n" % line
print text

3

对于这个答案的扩展 https://dev59.com/P2gu5IYBdhLWcg3wASWO#11664652,你可以检查一行是否存在,而不是任何停用词。

content = []
while True:
    line = raw_input()
    if line:
        content.append(line)
    else:
        break

您将得到一个列表中的行,然后使用 \n 连接以获得您想要的格式。
print '\n'.join(content)

3

试试这个

import sys

lines = sys.stdin.read().splitlines()

print(lines)

输入:

1

2

3

4

输出: ['1', '2', '3', '4']


2

我自己也曾经为这个问题苦苦挣扎了很长时间,因为我想找到一种方法来读取多行用户输入而不需要用户用Control D(或停止词)来终止它。最终我在Python3中找到了一种方法,使用pyperclip模块(您需要使用pip install安装)。以下是一个示例,它接受IP列表。

import pyperclip

lines = 0

while True:
    lines = lines + 1 #counts iterations of the while loop.

    text = pyperclip.paste()
    linecount = text.count('\n')+1 #counts lines in clipboard content.

    if lines <= linecount: # aslong as the while loop hasn't iterated as many times as there are lines in the clipboard.
        ipaddress = input()
        print(ipaddress)

    else:
        break

对我来说,这正是我所需要的;接收多行输入,执行必要的操作(这里是简单的打印),并在处理完最后一行后跳出循环。希望它对你也同样有用。

注:Original Answer翻译成“最初的回答”

1

使用Python 3,您可以将每行分配给data

while data := input():
    print("line", data)

太棒了!另外,为了澄清一下,那个循环在输入为空的情况下结束。可能并不明显对每个人来说。 - Trasp

1

当你知道你想让Python读取的确切行数时,从提示/控制台中读取多行的最简单方法是使用列表推导式

lists = [ input() for i in range(2)]

上面的代码读取2行。并将输入保存在列表中。


1

sys.stdin.read() 可以用于获取用户的多行输入。例如:

>>> import sys
>>> data = sys.stdin.read()
  line one
  line two
  line three
  <<Ctrl+d>>
>>> for line in data.split(sep='\n'):
  print(line)

o/p:line one
    line two
    line three

0
Python Prompt Toolkit 是一个非常好的工具,但上面的例子并没有很好地展示它。更好的例子是 examples 目录下的 get-multiline-input.py。
#!/usr/bin/env python
from prompt_toolkit import prompt
from prompt_toolkit.formatted_text import HTML


def prompt_continuation(width, line_number, wrap_count):
    """
    The continuation: display line numbers and '->' before soft wraps.
Notice that we can return any kind of formatted text from here.
The prompt continuation doesn't have to be the same width as the prompt
which is displayed before the first line, but in this example we choose to
align them. The `width` input that we receive here represents the width of
the prompt.
    """
    if wrap_count > 0:
        return " " * (width - 3) + "-> "
    else:
        text = ("- %i - " % (line_number + 1)).rjust(width)
        return HTML("<strong>%s</strong>") % text


if __name__ == "__main__":
    print("Press [Meta+Enter] or [Esc] followed by [Enter] to accept input.")
    answer = prompt(
    "Multiline input: ", multiline=True, prompt_continuation=prompt_continuation
)
    print("You said: %s" % answer)

使用此代码,您可以获得多行输入,即使在输入后续行之后,每行也可以进行编辑。还有一些不错的附加功能,例如行号。输入以按下 escape 键然后按下 enter 键结束:

~/Desktop ❯ py prompt.py
按 [Meta+Enter] 或 [Esc] 然后按 [Enter] 接受输入。
多行输入:第一行文本,然后按 enter
- 2 - 第二行文本,然后按 enter
- 3 - 第三行文本,箭头键可用于移动,按 enter
- 4 - 并且可以根据需要编辑行,直到您
- 5 - 按下 escape 键然后按下 enter 键
您说:第一行文本,然后按 enter
第二行文本,然后按 enter
第三行文本,箭头键可用于移动,按 enter
并且可以根据需要编辑行,直到您
按下 escape 键然后按下 enter 键
~/Desktop ❯


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接