python中print和input的底层实现

时间:2023-03-09 17:49:32
python中print和input的底层实现

print

print的底层通过sys.stdout.write() 实现

import sys

print('hello')
print('world')
print(520)
sys.stdout.write('hello')
sys.stdout.write('world')
# sys.stdout.write(520) # TypeError: write() argument must be str, not int

控制台输出
```python
hello
world
520
helloworld


<br>
## 小结
sys.stdout.write()和print都是向屏幕输出内容,区别在于:
- sys.stdout.write()没有自动换行,print有
- <b><font color='#ff0000'>sys.stdout.write()只能写入字符串</font></b>,print可以写入任意数据类型 <br>
## input
Python3中的input()使用`sys.stdin.readline()`实现
```python
import sys a = sys.stdin.readline()
print(a, len(a)) b = input()
print(b, len(b))

控制台输出结果
```python
hello
hello
6
hello
hello 5

为什么两个长度不一样呢?这是因为<b><font color='#ff0000'>sys.stdin.readline()把结尾的换行符也算进去了</font></b>,6和hello不在一行也可以证明这一点
<br>
sys.stdin.readline()还可以传入参数,指定读取前几个字符 ```python
c = sys.stdin.readline(2)
print(c, len(c))

控制台输出

hello
he 2

当传入的参数大于输入的字符的长度时,输出所有字符
```python
c = sys.stdin.readline(10)
print(c, len(c))

<br>
控制台输出结果
```python
hello
hello
6

当传入的参数为负数时,表示获取整行
```python
d = sys.stdin.readline(-3)
print(d, len(d))

<br>
控制台输出结果
```python
helloworld
helloworld
11

当一次没有读取完时,下一次读取将会从上次的结束位置开始,这一点与文件类似
```python
c = sys.stdin.readline(6)
print(c, len(c))

d = sys.stdin.readline(4)

print(d, len(d))

<br>
控制台输出结果
```python
helloworld
hellow 6
orld 4

sys.stdin.readline()不能像input一样传入字符串作为提示信息
```python
username = input("username:")

password = sys.stdin.readline("password:")

<br>
控制台输出结果
```python
username:robin
Traceback (most recent call last):
File "D:/input_print.py", line 50, in <module>
password = sys.stdin.readline("password:")
TypeError: 'str' object cannot be interpreted as an integer

## 小结
sys.stdin.readline()和input都是输入内容,区别在于:
- sys.stdin.readline()读取所有字符,包括结尾的换行符
- sys.stdin.readline()可以设置单次读取的字符个数,iinput不行
- sys.stdin.readline()不能设置提示信息,input可以