【Python】重定向 Stream 到文件


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM