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

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

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
>>> 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
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄