pat*_*ick 5 python stdin user-input sys
我正在使用 Py 3.6 中的用户输入编写脚本。
在脚本中,用户被要求在 shell 中输入一个文本部分——可能包含新行。然后输入的文本将保存到 Python 变量中以供进一步处理。
由于用户输入可能包含换行符,我想我不能使用input()但正在使用sys.stdin.read()(如建议here)。
读入输入工作正常,但要结束用户输入,用户必须按下 Return 键,然后使用组合键CTRL + d(请参阅此处)。(请参阅下面的当前程序)
sys.stdin.read通过按回车键来结束他们的输入(参见下面的预期程序)编辑:对当前过程的任何其他简化CTRL + d也表示赞赏。
这是可行的吗?
这里有一些技巧,但我想也许有更好的方法
# 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`
Run Code Online (Sandbox Code Playgroud)
使用下面复制的当前代码,用户必须
1) 粘贴文本 2) 点击RETURN结束输入 3) 点击Ctrl+d移动到下一个文件
我想将其减少为:
1) 粘贴文本 2) 点击RETURN结束输入并移动到下一个文件
在 MacOSX 上运行 Python 3.5.6,使用终端进行文本输入。任何帮助深表感谢!
根据您在评论中的回复,如果可以接受空行终止(即您的输入文本本身不能包含换行符,除非终止输入),那么引用很简单:
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
Run Code Online (Sandbox Code Playgroud)
我一直在提到的另一个选择,尽管我不太喜欢支持这种方法的假设。您可以读取您的输入并记录每次输入的时间。您可以定义一个时间限制,过了该时间限制您就可以放心地假设它不是作为单个块复制粘贴的一部分。然后,单独的换行符被假定为用户输入的结束。例如:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
837 次 |
| 最近记录: |