gpt4 book ai didi

python - input() 和 sys.stdin 有什么区别?

转载 作者:行者123 更新时间:2023-11-28 22:44:27 24 4
gpt4 key购买 nike

我是 python 的新手,正在尝试在线解决一些编码问题。我经常遇到 sys.sdnin 接受输入。我想知道 input()sys.stdin 在操作上有何不同?

最佳答案

通过代码示例进行说明

我一直在问自己同样的问题,所以我想出了这两个片段,通过模拟后者与前者:

import sys

def my_input(prompt=''):
print(prompt, end='') # prompt with no newline
for line in sys.stdin:
if '\n' in line: # We want to read only the first line and stop there
break
return line.rstrip('\n')

这是一个更精简的版本:

import sys

def my_input(prompt=''):
print(prompt, end='')
return sys.stdin.readline().rstrip('\n')

这两个片段与 input() 函数的不同之处在于它们不检测文件结尾(见下文)。

通过文档澄清

官方文档是这样描述函数input()的:

input([prompt])

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 a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

这就是sys.stdin描述:

sys.stdin

File object used by the interpreter for standard input.
stdin is used for all interactive input (including calls to input());
These streams (sys.stdin, sys.stdout and sys.stderr) are regular text files like those returned by the open() function. [...]

因此,input() 是一个函数,而 sys.stdin 是一个对象(一个文件对象)。因此,它有许多属性,您可以在解释器中探索这些属性:

> dir(sys.stdin)

['_CHUNK_SIZE',
'__class__',
'__del__',
'__delattr__',
'__dict__',
'__dir__',

...

'truncate',
'writable',
'write',
'write_through',
'writelines']

并且您可以单独显示,例如:

> sys.stdin.mode
r

它还有一些方法,比如readline(),它“从文件中读取一行;在字符串末尾留下一个换行符(\n),如果文件不以换行符结尾,并且仅在文件的最后一行被省略。这使得返回值明确;如果 f.readline() 返回空字符串,则已到达文件末尾,而空行由 '\n' 表示,这是一个仅包含单个换行符的字符串。"( 1 )

全面实现

最后一个方法允许我们完全模拟 input() 函数,包括它的 EOF 异常错误:

def my_input(prompt=''):
print(prompt, end='')
line = sys.stdin.readline()
if line == '': # readline() returns an empty string only if EOF has been reached
raise EOFError('EOF when reading a line')
else:
return line.rstrip('\n')

关于python - input() 和 sys.stdin 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29527023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com