您如何从Python的stdin中读取信息?

Python supports following ways to read an input from stdin (standard input),

Python支持以下方式从stdin(标准输入)读取输入

1)使用sys.stdin (1) Using sys.stdin)

sys.stdin is a file-like object on which we can call functions read() or readlines(), for reading everything or read everything and split by newline automatically.

sys.stdin是一个类似于文件的对象,我们可以在其上调用函数read()readlines() ,以读取所有内容或读取所有内容并自动由换行符拆分。

Example:

例:

from sys import stdin

input = stdin.read(1)
user_input = stdin.readline()
amount = int(user_input)

print("input = {}".format(input))
print("user_input = {}".format(user_input))
print("amount = {}".format(amount))

Output

输出量

123
input = 1
user_input = 23

amount = 23

2)使用input() (2) Using input())

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to string (stripping a trailing newline) and returns that.

如果存在提示参数,则将其写入到标准输出中,而无需尾随换行符。 然后,该函数从输入中读取一行,将其转换为字符串(带末尾的换行符)并返回。

Example:

例:

test = input('Input any text here --> ')
print("Input value is: ", test)

Output

输出量

Input any text here --> Hello Readers!
Input value is:  Hello Readers!

Recommended posts

推荐的帖子

翻译自: https://www.includehelp.com/python/how-do-you-read-from-stdin-in-python.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值