Python基础教程讲解——print输出重定向介绍
本期的Python基础教程给大家讲print输出相关知识点,敲黑板听课了!
Python中调试程序使用最多的是print(),在使用print()打印时事实上是调用了 sys.stdout.write()。不过print在把内容打印到控制台后,追加了一个换行符(linefeed)。以下例程中,print和sys.stdout.write()是等价的:
sys.stdout.write('Hello Worldn')
print('Hello World')
在Python中, sys.stdin、sys.stdout和sys.stderr分别对应解释器的标准输入、标准输出和标准出错流。在程序启动时,这些对象的初值由sys.stdin、sys.__stdout__和sys.__stderr__保存,比便于恢复标准流对象。如下所示:
print(sys.stdout) # <_io.TextIOWrapper name='' mode='w' encoding='UTF-8'>
print(sys.stdin) # <_io.TextIOWrapper name='' mode='r' encoding='UTF-8'>
print(sys.stderr) # <_io.TextIOWrapper name='' mode='w' encoding='UTF-8'>
print(sys.__stdout__) # <_io.TextIOWrapper name='' mode='w' encoding='UTF-8'>
print(sys.__stdin__) # <_io.TextIOWrapper name='' mode='r' encoding='UTF-8'>
print(sys.__stderr__) # <_io.TextIOWrapper name='' mode='w' encoding='UTF-8'>
如果我们要把内容重定向到文本中去时,该如何操作呢?我们先看下普通的文本对象和标准输出对象的区别。如下所示:
print(dir(sys.stdout))
"""
['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__',
'__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__',
'__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__',
'__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable',
'_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors',
'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable',
'readline', 'readlines', 'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write',
'write_through', 'writelines']
"""
with open('redirect.txt', 'w') as f:
print(f) # <_io.TextIOWrapper name='redirect.txt' mode='w' encoding='cp1252'> print(dir(f)) """ ['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'write_through', 'writelines'] """
可见两者都属于文件对象,其中所包含的方法也都相同,比如write、read等等。所以,如果把文件对象的引用赋值给sys.stdout,那么print调用的即为文件对象的write方法,这样就实现了重定向。其实在之前的Python基础教程中有跟大家讲古。代码如下所示:
with open('redirect.txt', 'w') as f:
sys.stdout = f print("Hello World")
重定向后,print打印的内容就从控制台搬到了文本上了,如下所示:
Python基础教程讲解——print输出重定向介绍
如果只是临时向文件中打印内容,之后仍然会在控制台上打印的话,应该先将原始的控制台引用对象保存下来,之后将该引用恢复到sys.stdout中。如下所示:
console = sys.stdout
redirection start
...
redirection end
sys.stdout = console
以上的实现方法并不优雅,典型的实现如下所示:
临时把标准输出重定向到一个文件,然后再恢复正常
with open('redirect.txt', 'w') as f:
oldstdout = sys.stdout sys.stdout = f try: help(__import__) finally: sys.stdout = oldstdout
print("Hello World")
Python基础教程讲解——print输出重定向介绍
接下来介绍Pyhton上下文管理器redirect_stdout实现重定向的方法。contextlib.redirect_stdout在Python 3.4加入。如下所示:
with open('redirect.txt', 'w') as f:
with contextlib.redirect_stdout(f): help(pow)
Python基础教程讲解——print输出重定向介绍
当然,其实redirect_stdout的内在实现逻辑也仅是保存控制台的引用,而后恢复如此而已。于是我们可以实现自己的redirect_stdout上下文管理器。如下所示:
@contextlib.contextmanager
def redirect_stdout(fileobj):
oldstdout = sys.stdout sys.stdout = fileobj try: yield fileobj finally: sys.stdout = oldstdout
def redirect4():
with open('redirect.txt', 'w') as f: with redirect_stdout(f): help(pow) print("Hello World")
更多的Python基础教程也会继续更新,大家有想学想看的内容也可以留言,我会整理出相关文章哈!
低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
第420期 Python 周刊
文章、教程或讲座 Python 数据科学教程:分析 Stack Overflow 2019 年开发者调查表**) https://www.youtube.com/watch?v=_P7X8tMplsw 在此 Python 编程视频中,我们将从 Stack Overflow 2019 年的开发者调查中学习如何下载和分析这些数据。对于任何想入门数据科学领域的人来说这都是非常好的实践。你将学到用不同方法分析这些数据。 大规模部署 Python 代码 https://instagram-engineering.com/python-at-scale-strict-modules-c0bb9245c834 这是我们发布的关于在 Instagram 大规模部署 Python 代码的第三篇文章!正如我们第一篇文章中所提到的,Instagram 服务器是数百万行 Python 代码的集合:每天数百次提交,每隔几分钟部署到生产环境中。以这种规模和速度使用 Python 时,我们遇到了一些痛点。 通过深度学习寻找受欢迎的菜肴 https://engineeringblog.yelp.com/2019/10...
- 下一篇
8道Python基础面试练习题
1.26个字母大小写成对打印,例如:Aa,Bb...... for i in range(26): print(chr(65+i)+chr(97+i)) 2.一个list包含10个数字,然后生成一个新的list,要求新的list里面的数都比之前的数多1 list=[2,3,6,4,7,5,1,8,9,0] list1=[] for i in list: list1.append(i+1) print(list1) 3.倒序取出每个单词的第一个字母,例如:I am a good boy!方法1 tre='I am a good boy!' t=tre.split() #print(t) t.reverse() list=[] #print(t) for i in t: list.append(i[0]) print(list) 方法2 a = "I AM A BOY" result = [] for i in a.split()[::-1]: result.append(i[0]) print(result) 4.输入一个自己的生日月份,用if和else判断一下当月是不是你的生日月第一种...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- Docker使用Oracle官方镜像安装(12C,18C,19C)
- CentOS7设置SWAP分区,小内存服务器的救世主
- SpringBoot2更换Tomcat为Jetty,小型站点的福音
- SpringBoot2整合Thymeleaf,官方推荐html解决方案
- MySQL8.0.19开启GTID主从同步CentOS8
- Linux系统CentOS6、CentOS7手动修改IP地址
- CentOS7编译安装Cmake3.16.3,解决mysql等软件编译问题
- SpringBoot2整合Redis,开启缓存,提高访问速度
- CentOS7编译安装Gcc9.2.0,解决mysql等软件编译问题
- Hadoop3单机部署,实现最简伪集群