python重定向文件_【Python】重定向 Stream 到文件

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

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

>>> import sys

>>> # 测试输出

...

>>> word = 'Exciting'

>>> n1 = print(word)

Exciting

>>> n1 # 因为print没有返回值,所以 n1 是空值

>>> type(n1)

>>> n2 = sys.stdout.write(word + '\n')

Exciting

>>> n2 # len(word) + len('\n') = 9

9

>>> type(n2)

>>> # 测试输入

...

>>> w1 = input()

hello

>>> w1

'hello'

>>> w2 = sys.stdin.readline()

hello

>>> w2 # w2 包括换行符

'hello\n'

sys.stdin 、sys.stdout 与 sys.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 "", line 1, in

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 "", line 3, in

EOFError: EOF when reading a line

>>> fin.close()

>>> sys.stdin = in_stream

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值