命令行Python应用程序中的多行用户输入 [英] Multiple lines user input in command-line Python application

查看:145
本文介绍了命令行Python应用程序中的多行用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在命令行Python应用程序中是否有任何简便的方法来处理多行用户输入

Is there any easy way to handle multiple lines user input in command-line Python application?

我一直在寻找答案而没有任何结果,因为我不想

I was looking for an answer without any result, because I don't want to:


  • 从文件中读取数据(我知道最简单的方法);

  • 创建任何GUI(让我们仅保留命令行,好吗?);

  • 逐行加载文本(它应该一次粘贴,而不是逐行粘贴,而不是逐行粘贴);

  • 分别处理每行(我想将整个文本作为字符串)。

  • read data from a file (I know, it's the easiest way);
  • create any GUI (let's stay with just a command line, OK?);
  • load text line by line (it should pasted at once, not typed and not pasted line by line);
  • work with each of lines separately (I'd like to have whole text as a string).

我要实现的是允许用户粘贴整个文本(包含多行)并捕获在完全命令行工具中作为一个字符串输入

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?

这很好,如果该解决方案在Linux和Windows环境中都可以工作(我听说例如某些解决方案可能会由于

It would be great, if the solution worked both in Linux and Windows environments (I've heard that e.g. some solutions may cause problems due to the way cmd.exe works).

推荐答案

import sys

text = sys.stdin.read()

粘贴后,您必须告诉python通过发送文件结束控制字符(Linux中的 ctrl + D ctrl + Z ,然后在Windows中依次输入 enter

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).

此方法也适用于管道。如果上述脚本称为 paste.py ,则可以

This method also works with pipes. If the above script is called paste.py, you can do


$ echo "hello" | python paste.py

text 将等于 hello\n 。在Windows中是相同的:

and text will be equal to "hello\n". It's the same in windows:


C:\Python27>dir | python paste.py

上面的命令会将 dir 的输出保存到 text 变量。使用管道提供输入时,无需手动键入文件结尾字符-创建输入的程序完成后,python将自动得到通知。

The above command will save the output of dir to the text variable. 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应用程序中的多行用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆