python怎么输入两行命令_命令行Python应用程序中的多行用户输入

1586010002-jmsa.png

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:

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?

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

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

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

$ echo "hello" | python paste.py

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

C:\Python27>dir | python paste.py

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值