前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Python】重定向 Stream 到

【Python】重定向 Stream 到

作者头像
py3study
发布2020-01-17 12:30:48
8510
发布2020-01-17 12:30:48
举报
文章被收录于专栏:python3python3

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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-05-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档