Python 系统模块 sys 中有三个变量 stdinstdoutstderr ,分别对应标准输入流、输出流与错误流。stdin 默认指向键盘, stdoutstderr 默认指向控制台。

print 方法与 sys.stdout.write()的作用基本相同,后者不会打印额外的符号,并且会将打印字符数作为返回值返回;intput 方法与 sys.stdin.readline() 也很类似,后者会读入输入的每一个字符,包括换行符。

>>> import sys
>>> # 测试输出
...
>>> word = 'Exciting'
>>> n1 = print(word)
Exciting
>>> n1 # 因为print没有返回值,所以 n1 是空值
>>> type(n1)
<class 'NoneType'>
>>> n2 = sys.stdout.write(word + '\n')
Exciting
>>> n2 # len(word) + len('\n') = 9
9
>>> type(n2)
<class 'int'>
>>> # 测试输入
...
>>> w1 = input()
hello
>>> w1
'hello'
>>> w2 = sys.stdin.readline()
hello
>>> w2 # w2 包括换行符
'hello\n'

sys.stdinsys.stdoutsys.stderr 是三个变量,这意味着我们可以将它们的值修改成我们需要的对象类型,比如文件对象。

文本作为输入流与错误流

>>> out = sys.stdout # 首先要将默认的输出流对象存起来
>>> fout = open('outfile', 'w')
>>> sys.stdout = fout
>>> for i in range(10):
... print(i)
...
>>> fout.close()
>>> sys.stdout = out # 回复默认输出流对象

现在在命令行 cat 一下 outfile 文件

$ cat outfile
0
1
2
3
4
5
6
7
8
9

重定向错误流的方法与之类似

>>> err = sys.stderr
>>> ferr = open('errfile', 'w')
>>> sys.stderr = ferr
>>> s # 输入一个没有声明过的变量
>>> ferr.close()
>>> sys.stderr = err

在命令行 cat errfile

$ cat errfile
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 's' is not defined

可以看到,之前在 python shell 中没有显示的错误日志,现在被写入到 errfile 里面了

文件作为输入流

先准备好要读入的文本文件

$ echo -e 'hello\nthis\nexcitng\nworld' > infile
$ cat infile
hello
this
excitng
world

在 python shell 中测试一下

>>> in_stream = sys.stdin
>>> fin = open('infile', 'r')
>>> sys.stdin = fin
>>> s = input()
>>> while s:
... print(s)
... s = input()
...
hello
this
excitng
world
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
EOFError: EOF when reading a line
>>> fin.close()
>>> sys.stdin = in_stream

【Python】重定向 Stream 到文件的更多相关文章

  1. Python第五天 文件访问 for循环访问文件 while循环访问文件 字符串的startswith函数和split函数 linecache模块

    Python第五天   文件访问    for循环访问文件    while循环访问文件   字符串的startswith函数和split函数  linecache模块 目录 Pycharm使用技巧( ...

  2. python爬虫之下载文件的方式总结以及程序实例

    python爬虫之下载文件的方式以及下载实例 目录 第一种方法:urlretrieve方法下载 第二种方法:request download 第三种方法:视频文件.大型文件下载 实战演示 第一种方法: ...

  3. python批量处理excel文件数据

    https://www.zhihu.com/question/39299070?sort=created 作者:水中柳影链接:https://www.zhihu.com/question/392990 ...

  4. [python]自动化将markdown文件转成html文件

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  5. python中的pth文件作用

    python中有一个.pth文件,该文件的用法是: 首先xxx.pth文件里面会书写一些路径,一行一个. 将xxx.pth文件放在特定位置,则可以让python在加载模块时,读取xxx.pth中指定的 ...

  6. python 函数初识和文件操作

    文件操作  打开文件:文件句柄 = open('文件路径', '模式')  打开文件的模式 w #以写的方式打开 (不可读,不存在则创建,存在则删除内容) a #以追加的模式打开(可读, 不存在则创建 ...

  7. 使用python求字符串或文件的MD5

    使用python求字符串或文件的MD5 五月 21st, 2008 #以下可在python3000运行. #字符串md5,用你的字符串代替'字符串'中的内容. import hashlib md5=h ...

  8. python中__init__.py文件的作用

    问题 在执行models.py时,报ImportError:No module named transwarp.db的错误,但明明transwarp下就有db.py文件,路径也没有错误.真是想不通.后 ...

  9. python下读取excel文件

    项目中要用到这个,所以记录一下. python下读取excel文件方法多种,用的是普通的xlrd插件,因为它各种版本的excel文件都可读. 首先在https://pypi.python.org/py ...

随机推荐

  1. Max answer(The Preliminary Contest for ICPC China Nanchang National Invitational)

    Alice has a magic array. She suggests that the value of a interval is equal to the sum of the values ...

  2. redis 有序集合类型

  3. Matlab 绘图实例

    概要   每次用 Matlab 绘图都要搜一堆资料设置一些参数,本次将绘图中的一些参数设置实例展示在这里,以备不时之需.暂包括折线图,面积图.   折线图实例   下图是效果图: 图 1:折线图效果图 ...

  4. MongoDB数据库CXX Driver编译

    最近项目需要,想要测试下MongoDB读写大量小图片的速度(单纯文件系统io效率比较低,想试试NoSQL能不能提速), 因为使用C++开发,所以使用MongoDB的CXX驱动,需要自己编译,下面记录整 ...

  5. 简单介绍Spring是什么?

    对于面试者回答什么是Spring,这个问题占6分分值,分值点分布:1.Spring的核心是一个轻量级(Lightweight)的容器(Container).2.Spring是实现IoC(Inversi ...

  6. CSS 负边距读后感

    最近看到一篇讲解CSS 负边距的文章: http://segmentfault.com/a/1190000003750411?utm_source=Weibo&utm_medium=share ...

  7. Android笔记(预安装APK)

    一般一个安卓的产品在出厂时,会预安装许多APK,关于这些APP,主要分为下面这几类 1.系统级别APK 这一类应用一般是:电话/设置或者厂家自己特定的应用. 2.系统预安装APK 因为商业原因,产品出 ...

  8. java基础1.5版后新特性 自动装箱拆箱 Date SimpleDateFormat Calendar.getInstance()获得一个日历对象 抽象不要生成对象 get set add System.arrayCopy()用于集合等的扩容

    8种基本数据类型的8种包装类 byte Byte short Short int Integer long Long float Float double Double char Character ...

  9. Error:linker command failed with exit code 1 (use -v to see invocation) - iOS

    今天在操作 CoreData 时,创建完 Create NSManagedObject Subclass...  后,工程中会自动生成四个文件,如下图所示:   此时此刻便以工程,激动人心的时刻来临了 ...

  10. ssm整合-错误3

    1.警告: Unknown version string [3.1]. Default version will be used. 因为Tomcat版本为7,支持3.1版本的为Tomcat 8: 2. ...