python的input和output

本文详细介绍了Python中的输入输出,包括stdout、stderr、stdin流的使用,以及如何编写自定义的myout和myin函数。通过实例展示了如何处理输入输出,解释了input函数的行为,特别是遇到EOF时的处理方式。文章最后提供了myout和myin的完整代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


说到python的输入输出,许多人都只知道 printinput。可是大家知道这背后的原理吗?今天我就在这篇文章里告诉大家,这背后的原理是什么。

1.输入输出文件-stdout,stderr及stdin

作为同我们平常用open函数返回的内容一样,都为_io.TextIOWrapperstdout,stderrstdin,他们也可以像我们平常操作一个文件一样操作:写入,读出,刷新……
不信,我们可以通过测试来证实一下:

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

那这样一来,有些人有疑问了:你怎么证明printinput就是用了他们呢?
很简单,我们只要看一看这两个函数的帮助就好了:

>>> 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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值