python重定向原理及实例,python重定向实例,1. 前言为了在Py
python重定向原理及实例,python重定向实例,1. 前言为了在Py
1. 前言
为了在Python编程中, 利用控制台信息, 我们需要对控制台输出进行接管(重定向)。在Python中,控制台输出的接口是sys.stdout,通过分析print与sys.stdout之间的关系,我们就可以实现控制台输出重定向了。
2. sys.stdout 与 print
当我们在 Python 中打印对象调用
print(obj)
的时候,事实上是调用了
# 在print(obj)的过程中, 会产生两次调用sys.stdout.write(obj)sys.stdout.write('\n')
所以, 我们只要创造一个替代的对象, 实现write方法, 就可以进行控制台输出重定向了.
3. 实战 之 同时重定向到控制台和文件
import sysclass __redirection__(object): def __init__(self, filepath): self.filepath = filepath self.buff = '' self.__console__ = sys.stdout sys.stdout = self def write(self, output_stream): self.buff += output_stream self.__console__.write(output_stream) f = open(self.filepath,'w') f.write(self.buff) f.close() def flush(self): self.buff = '' def __del__(self): sys.stdout = self.__console__if __name__ == '__main__': def main(): r_obj=__redirection__(r'd:/temp/test.txt') print('hello') print('__redirection__') main()
python重定向原理及实例
相关内容
- BioPython-2,,关于Seq对象的内容
- python之图片文字识别,python文字识别,总体思路:
- Python 帮你玩微信跳一跳 GitHub Python脚本,githubpython,前言
- python基础数据类型,,1,int #数字(
- 关于python -os.mkdir(str)方法的使用记录,python-os.mkdir,这几
- python练习册0005,python0005, 第 0005 题:
- Python爬取全书网小说,免费看小说,,什么是网络爬虫网
- python中高阶函数与装饰器(2),,函数返回值为内置函数
- python连接MySQL,, 再python3
- PyCharm中Dictionary与Python package的区别,pycharmpython,Dictio
评论关闭