![51c6c8af73e47ea792ab9be79ccc20df.png](https://img-blog.csdnimg.cn/img_convert/51c6c8af73e47ea792ab9be79ccc20df.png)
概述
当我们在Python的print打印时,我们到底在使用什么? 其实print语句不过是Python简便使用的特性体验而已,其背后就是sys.stdout对象的简单接口,即我们也可以利用sys.stdout完成所有print打印行为,比如打印Hello, world!。
import syssys.stdout.write('Hello, world!')
示例结果:
Hello, world!
再者
python import syss1 = 'Hello,'s2 = 'world!'print(s1, s2, end='')sys.stdout.write(str(s1) + ' ' + str(s2) + '')
示例结果:
Hello, world!Hello, world!
重定向输出流
我们已经知道print对sys.stdout的依赖,那么我们能否将sys.stdout赋值为标准输出流以外的东西,即将print的文字传送到其他地方。
import syss1 = 'Hello,'s2 = 'world!'sys.stdout = open('hello.txt', 'a')...print(s1, s2)print(s2, s1)
hello.text内容:
Hello, world!world! Hello,
可以看到标准输出流并没有打印任何信息,而需要被打印的内容全部被写入hello.txt文件中,这是为何? 因为我们把sys.stdout重设成已经打开的文件对象,重设之后,程序中所有的print都会将文字输出至文件hello.txt中,即进程中只有一个sys模块,通过这种方式就可以将所有的print进行重定向。当然我们也可以对单个print进行重定向,即上节介绍的print函数中的file参数完成重定向,这也是为何print定义file之后不会进行原始输出流的操作,即屏幕没有打印该次print函数的字符串信息。