python的input和output
说到python的输入输出,许多人都只知道
print
和
input
。可是大家知道这背后的原理吗?今天我就在这篇文章里告诉大家,这背后的原理是什么。
1.输入输出文件-stdout,stderr及stdin
作为同我们平常用open
函数返回的内容一样,都为_io.TextIOWrapper
的stdout
,stderr
及stdin
,他们也可以像我们平常操作一个文件一样操作:写入,读出,刷新……
不信,我们可以通过测试来证实一下:
>>> import sys
>>> type(open("con"))
<class '_io.TextIOWrapper'>
>>> type(sys.stdout)
<class '_io.TextIOWrapper'>
>>> type(sys.stderr)
<class '_io.TextIOWrapper'>
>>> type(sys.stderr)
<class '_io.TextIOWrapper'>
那这样一来,有些人有疑问了:你怎么证明print
和input
就是用了他们呢?
很简单,我们只要看一看这两个函数的帮助就好了:
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
>>> help(input)
Help on built-in function input in module builtins:
input(prompt=None, /)
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF