【问题标题】:How can I use raw_input to receive input from stdin in python 2.7? [duplicate]如何在 python 2.7 中使用 raw_input 从标准输入接收输入? [复制]
【发布时间】:2016-01-19 03:53:13
【问题描述】:

为了在 python 2.7 中接收来自标准输入的输入,我通常使用import sys 并使用sys.stdin。但是,我看到过使用raw_input 接收来自标准输入的输入的示例,包括多行输入。我如何准确地使用 raw_input 代替 sys.stdin?这是一个示例问题:

输入.txt:

Print
me
out

我正在运行这个命令:

cat input.txt | python script.py

我可以在 script.py 中添加什么,以便它使用raw_input 打印出所有输入行?

【问题讨论】:

    标签: python python-2.7 stdin raw-input


    【解决方案1】:

    你可以这样做:

    while True:
        try:
            print raw_input()
        except EOFError:
            break
    

    raw_input 只会从标准输入返回单行,并在读取 EOF 时抛出 EOFError。

    【讨论】:

    • 什么时候会抛出 EOFError?
    • 为什么会抛出 EOF?
    • 另外,每个raw_input 只接收一行标准输入?
    • EOF 是您的操作系统表示没有什么可以从读取源读取的方式。 raw_input 被定义为不断从标准输入返回行,直到到达 EOF,当到达时它会抛出一个 EOFError。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    相关资源
    最近更新 更多