[英]Multiple lines user input in command-line Python application
Is there any easy way to handle multiple lines user input in command-line Python application ? 有没有简单的方法来处理命令行Python应用程序中的多行用户输入 ?
I was looking for an answer without any result, because I don't want to : 我正在寻找一个没有任何结果的答案,因为我不想 :
What I would like to achieve is to allow user pasting whole text (containing multiple lines) and capture the input as one string in entirely command-line tool . 我想要实现的是允许用户粘贴整个文本 (包含多行) 并在完全命令行工具中将输入捕获为一个字符串 。 Is it possible in Python?
在Python中有可能吗?
It would be great, if the solution worked both in Linux and Windows environments (I've heard that eg some solutions may cause problems due to the way cmd.exe works). 如果解决方案在Linux和Windows环境中都能工作,那就太好了(我听说过,例如某些解决方案可能会因cmd.exe工作原因而导致问题)。
import sys
text = sys.stdin.read()
After pasting, you have to tell python that there is no more input by sending an end-of-file control character ( ctrl + D in Linux, ctrl + Z followed by enter in Windows). 粘贴之后,你必须通过发送文件结束控制字符(Linux中的ctrl + D , ctrl + Z然后在Windows中输入 )告诉python没有更多的输入。
This method also works with pipes. 此方法也适用于管道。 If the above script is called
paste.py
, you can do 如果上面的脚本名为
paste.py
,则可以这样做
$ echo "hello" | python paste.py
and text
will be equal to "hello\\n"
. 和
text
将等于"hello\\n"
。 It's the same in windows: 它在Windows中是一样的:
C:\Python27>dir | python paste.py
The above command will save the output of dir
to the text
variable. 上面的命令会将
dir
的输出保存到text
变量中。 There is no need to manually type an end-of-file character when the input is provided using pipes -- python will be notified automatically when the program creating the input has completed. 当使用管道提供输入时,无需手动键入文件结束字符 - 当创建输入的程序完成时,将自动通知python。
You could get the text from clipboard without any additional actions which raw_input()
requires from a user to paste the multiline text: 您可以从剪贴板获取文本,而无需用户使用
raw_input()
要求粘贴多行文本的任何其他操作:
import Tkinter
root = Tkinter.Tk()
root.withdraw()
text = root.clipboard_get()
root.destroy()
See also How do I copy a string to the clipboard on Windows using Python? 另请参阅如何使用Python将字符串复制到Windows上的剪贴板?
Use : 采用 :
input = raw_input("Enter text")
These gets in input as a string all the input. 这些输入作为字符串输入所有输入。 So if you paste a whole text, all of it will be in the
input
variable. 因此,如果粘贴整个文本,则所有文本都将在
input
变量中。
EDIT: Apparently, this works only with Python Shell on Windows. 编辑:显然,这只适用于Windows上的Python Shell。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.