【问题标题】:Reading from sys.stdin, ending user input with RETURN从 sys.stdin 读取,用 RETURN 结束用户输入
【发布时间】:2019-01-10 16:39:46
【问题描述】:

我正在使用 Py 3.6 中的用户输入编写脚本。

在脚本中,要求用户在 shell 中输入一个文本部分 - 可能包含新行。然后将输入的文本保存到 Python 变量中以供进一步处理。

由于用户输入可能包含换行符,我想我不能使用input(),而是使用sys.stdin.read()(建议here)。

问题

在输入中读取工作正常,但要结束用户输入,用户必须按 Return,然后使用组合键 CTRL + d(请参阅 here)。 (请参阅下面的当前程序

问题

  • 我希望用户可以通过按回车键来结束对sys.stdin.read 的输入(参见下面的预期过程

编辑:也感谢使用 CTRL + d 对当前流程进行的任何其他简化。

  • 这可行吗?

  • 有一些 hacks here 但我认为也许有更好的方法

当前代码

    # display text on screen
    print("Review this text\n" + text)
    # user will copy and paste relevant items from text displayed into Terminal
    user_input =  sys.stdin.read() 
    print ("hit ctrl + d to continue")
    # process `user_input`

当前程序

使用下面复制的当前代码,用户必须

1) 粘贴文本 2) 点击RETURN 结束输入 3) 点击Ctrl+d 移动到下一个文件

预期过程

我想将其简化为:

1) 粘贴文本 2) 点击RETURN 结束输入并移动到下一个文件

在 MacOSX 上运行 Python 3.5.6,使用终端进行文本输入。 非常感谢任何帮助!

【问题讨论】:

  • 你可能想要print ("hit ctrl + d to continue")读取操作之前。
  • 这是什么操作系统?
  • 如果输入可能包含多行,那么您如何想象可以将行之间的返回与结束输入的返回区分开来?
  • 您对切换到 GUI 感觉如何?使用文本字段和提交按钮可能会更好。
  • @MadPhysicist 这是 MacOS High Sierra 10.13.6 对print 操作的调用也很好,仍在 WIP 中

标签: python user-input stdin sys


【解决方案1】:

根据您在评论中的回复,如果可以接受以空行终止(即您的输入文本不能单独包含换行符,除非终止输入),那就是微不足道的引用:

user_input = ''          # User input we'll be adding to
for line in sys.stdin:   # Iterator loops over readline() for file-like object
    if line == '\n':     # Got a line that was just a newline
        break            # Break out of the input loop
    user_input += line   # Keep adding input to variable

我一直在提到的另一个选项,尽管我不太喜欢支持这种方法的假设。您可以阅读您的输入并记录每个输入的时间。您可以定义一个时间限制,在此之后您可以轻松地假设它不是作为单个块复制粘贴的一部分。然后假设单独跟随换行符是用户输入的结束。例如:

import sys
import time

COPY_PASTE_LIMIT = 0.5  # For instance 500ms
                        # Presuming platform time precision
                        # greater then whole seconds.

user_input = ''
last = 0  # We'll also later terminate when input was nothing
          # but an initial empty line.
for line in sys.stdin:
    now = time.time()
    if line == '\n' and (now - last > COPY_PASTE_LIMIT or last == 0):
        break
    last = now
    user_input += line

print(user_input)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多