简体   繁体   English

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

[英]What is the difference between input() and sys.stdin?

I am new to python and trying some coding problems online.我是 python 的新手,并在网上尝试了一些编码问题。 i come across sys.sdnin a lot for accepting input.我经常遇到 sys.sdnin 接受输入。 I would like to know how input() and sys.stdin differs in action?我想知道input()sys.stdin在作用上有何不同?

Clarification through Code Examples通过代码示例澄清

I've been asking myself the same question, so I came up with these two snippets, which clarify how sys.stdin and input() differ by emulating the latter with the former:我一直在问自己同样的问题,所以我想出了这两个片段,通过模拟后者与前者来阐明sys.stdininput()不同之处:

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

Here is a more condensed version:这是一个更精简的版本:

import sys

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

Both these snippets differ from the input() function in that they do not detect the End Of File (see below).这两个片段与input()函数的不同之处在于它们不检测文件结尾(见下文)。

Clarification through Documentation通过文件澄清

This is how the official documentation describes the function input() :这是官方文档如何描述函数input()

input([prompt])输入([提示])

If the prompt argument is present, it is written to standard output without a trailing newline.如果存在 prompt 参数,则将其写入标准输出,而没有尾随换行符。 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.读取 EOF 时,会引发 EOFError。

And here's how sys.stdin is described:以下sys.stdin的描述方式:

sys.系统。 stdin标准输入

File object used by the interpreter for standard input.解释器用于标准输入的文件对象。
stdin is used for all interactive input (including calls to input()); stdin 用于所有交互式输入(包括对 input() 的调用);
These streams (sys.stdin, sys.stdout and sys.stderr) are regular text files like those returned by the open() function.这些流(sys.stdin、sys.stdout 和 sys.stderr)是与 open() 函数返回的那些一样的常规文本文件。 [...] [...]

So whereas input() is a function, sys.stdin is an object (a File object).因此input()是一个函数,而sys.stdin是一个对象(一个 File 对象)。 As such, it has a number of attributes, which you can explore in the interpreter, with:因此,它具有许多属性,您可以在解释器中探索这些属性:

> dir(sys.stdin)

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

  ...

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

and which you can display individually, for instance:并且您可以单独显示,例如:

> sys.stdin.mode
r

It also has methods, such as readline() , which " reads a single line from the file; a newline character (\\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn't end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\\n', a string containing only a single newline. " ( 1 )它还有一些方法,例如readline() ,它从文件中读取一行;在字符串的末尾留下一个换行符 (\\n),如果文件不以换行符结尾。这使得返回值明确;如果 f.readline() 返回一个空字符串,则表示已到达文件末尾,而空行由 '\\n' 表示,一个字符串仅包含一个换行符。 ” ( 1 )

Full implementation全面实施

This last method allows us to fully emulate the input() function, including its EOF Exception error:最后一个方法允许我们完全模拟 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')

Here's something to get you started:这里有一些东西可以让你开始:

The builtin function input reads a line of input from the standard input stream , optionally with a message prompt.内置函数input标准输入流中读取一行输入,可选地带有消息提示。 Be careful with the prompt, though, because the result of:但是,请注意提示,因为结果如下:

result = input('Do you want to do whatever? ')  ## doesn't work how you'd expect
if result.lower() in ('y', 'ye', 'yes', 'yup', 'ya'):
    do_whatever()
    ...
else:
    do_something_else()
    ...

..will include the prompt string as well (and so will never be equal to 'y'/'yes'/etc). .. 也将包含提示字符串(因此永远不会等于 'y'/'yes'/etc)。 In my opinion, it is better to print the prompt string first and then call input with no args, like so:在我看来,最好先打印提示字符串,然后不带参数调用 input,如下所示:

print('Do you want to do whatever?')
result = input()  ## notice that there is no prompt string passed to input()
if result.lower() in ('y', 'ye', 'yes', 'yup', 'ya'):
    do_whatever()
    ...
else:
    do_something_else()
    ...

So, to recap, the builtin function input reads input from the standard input stream ( sys.stdin ), and the builtin function print prints output to the standard output stream ( sys.stdout ).因此,回顾一下,内置函数input标准输入流( sys.stdin ) 读取输入,内置函数print输出打印到标准输出流( sys.stdout )。 There's a third one as well, the standard error stream ( sys.stderr ), to which unhandled exceptions get printed.还有第三个,标准错误流sys.stderr ),未处理的异常被打印到其中。

Usually, you don't have to worry about it too much.通常,您不必担心太多。 It's just when building IDEs and frameworks and such.这只是在构建 IDE 和框架等时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM