如何读取多行原始输入?

Posted

技术标签:

【中文标题】如何读取多行原始输入?【英文标题】:How to read multiple lines of raw input? 【发布时间】:2012-07-24 18:04:27 【问题描述】:

我想创建一个接受多行用户输入的 Python 程序。例如:

This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.

如何接收多行原始输入?

【问题讨论】:

如果您正在接受多行输入,您如何知道输入何时结束? 有一个循环接受 raw_input 直到用户输入“完成”或其他内容。 我猜您的目标是用户输入,但您可以在提示符中添加换行符 \n,例如:raw_input('foo\nbar: ') @felix001 你只想要raw_input 解决方案还是直接从stdin 获取输入? 你可以试试这个链接daniweb.com/software-development/python/threads/269208/… 【参考方案1】:

你觉得这个怎么样?我模仿了telnet。 sn-p 非常不言自明:)

#!/usr/bin/env python3

my_msg = input('Message? (End Message with <return>.<return>) \n>> ')

each_line = ''
while not each_line == '.':
    each_line = input('>> ')
    my_msg += f'\neach_line'

my_msg = my_msg[:-1]  # Remove unwanted period.

print(f'Your Message:\nmy_msg')

【讨论】:

【参考方案2】:

Python Prompt Toolkit 实际上是一个很好的答案,但上面的示例并没有真正显示出来。一个更好的例子是示例目录中的 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)

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

~/Desktop ❯ py prompt.py 按 [Meta+Enter] 或 [Esc] 然后按 [Enter] 接受输入。 多行输入:第一行文字,然后回车 - 2 - 第二行文字,然后回车 - 3 - 第三行文字,方向键可左右移动,回车 - 4 - 可以根据需要编辑行,直到您 - 5 - 按退出键,然后按回车键 你说:第一行文字,然后输入 第二行文字,然后输入 第三行文字,方向键可左右移动,回车 并且可以根据需要编辑行,直到您 按退出键,然后按回车键 ~/桌面❯

【讨论】:

【参考方案3】:

或者,您可以尝试sys.stdin.read(),它返回整个输入直到EOF

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

【讨论】:

如果您想接收具有多个空行的文本或任何其他数据,此解决方案是完美的。它在遇到 EOF 时停止(Ctrl+D;在 Windows 上为 Ctrl+Z)。【参考方案4】:

一种更简洁的方法(没有停用词 hack 或 CTRL+D)是使用 Python Prompt Toolkit

我们可以这样做:

from prompt_toolkit import prompt

if __name__ == '__main__':
    answer = prompt('Paste your huge long input: ')
    print('You said: %s' % answer)

即使是长的多行输入,它的输入处理也非常有效。

【讨论】:

【参考方案5】:

这是用python>3.5版本编写代码的最佳方式

a= int(input())
if a:
    list1.append(a)
else:
    break

即使你想限制你可以去的值的数量

while s>0:
a= int(input())
if a:
    list1.append(a)
else:
    break
s=s-1

【讨论】:

【参考方案6】:

当您知道 确切的行数您希望 Python 读取时,从提示/控制台读取多行的最简单方法是 列表理解

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

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

【讨论】:

【参考方案7】:

*我自己在这个问题上苦苦挣扎了很长时间,因为我想找到一种方法来读取多行用户输入,而无需用户使用 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

对我来说,这正是我想要的;接受多行输入,执行所需的操作(这里是简单的打印),然后在处理最后一行时中断循环。希望对您也有同样的帮助。

【讨论】:

【参考方案8】:

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

【讨论】:

【参考方案9】:

试试这个

import sys

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

print(lines)

输入:

1

2

3

4

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

【讨论】:

【参考方案10】:

只是扩展这个答案https://***.com/a/11664652/4476612 而不是任何停用词,您可以只检查一行是否存在

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

你会得到一个列表中的行,然后用 \n 加入你的格式。

print '\n'.join(content)

【讨论】:

【参考方案11】:
sentinel = '' # ends when this string is seen
for line in iter(raw_input, sentinel):
    pass # do things here

要将每一行作为字符串,您可以这样做:

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

Python 3:

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

【讨论】:

我成为 Python 达人已经 6 年了,但我从来不知道iter() 的其他形式。先生,您真是个天才! 如何将EOF设置为哨兵字符? @Randy 你可以让它看起来不那么漂亮iter(lambda: raw_input('prompt'), sentinel) 请注意,在 Python 3 中,raw_input 现在是 input @wecsam 现在添加了这一点,以使所有 python 的答案都完整【参考方案12】:

继续阅读行,直到用户输入一个空行(或将 stopword 更改为其他内容)

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

【讨论】:

以上是关于如何读取多行原始输入?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Spring Batch 读取一个单元格中包含多行的 CSV 文件?

如何从用户那里获取多行输入[重复]

将多行(读取为单行/输入)粘贴到 Spyder 控制台

C ++从文件中读取多行到单个字符串

如何读取多行 fwf 格式,其中行可能流或不流多行

七.sed多行模式和循环