2014-04-10 26 views
2

因此,我有一個程序將程序的輸出寫入文本文件,但不會寫出所有打印輸出到文本文件。有什麼方法可以增加這個嗎?這裏是一個代碼示例:如何增加在python中寫入文件的行數

import sys 
sys.stdout = open('thefile.txt', 'w') 
#Lots of printing here, but not all is written to the text file. 

有沒有辦法增加這個限制?或沒有? 編輯:沒關係,我剛剛發現了這個問題,我很早就意外地結束了這個程序。

+0

呃,你爲什麼要這樣做? – metatoaster

+1

@metatoaster - 像標準的重定向一樣是相當普遍的做法 - 對捕獲程序可能嘗試顯示的調試語句很有用。如果程序是一個窗口化的程序,並且'sys.stdout'指向一個空文件句柄,那麼這個特別有用。 –

+0

@gddc我知道爲什麼,但通常這不是典型腳本的第一件事,我只是希望OP確定這是確切的用例,而不是因爲他想用'print'寫入文件。 – metatoaster

回答

3

你最有可能缺少做同樣的事情sys.stderr。但是,你不應該那樣做。如果你想輸出和錯誤去到一個文件只需要調用你的程序像

python prog.py >thefile.txt 2>&1 
+2

程序或腳本通常最好是自包含的,而不是依靠額外的shell腳本。這裏使用的特性也是Python中常用的常用文檔。 –

2

您看到的輸出完全有可能是sys.stderr以及sys.stdout。爲了測試,你可以使用相同的文件句柄在兩個地方:

fh = open('thefile.txt', 'w') 
stdout_, stderr_ = sys.stdout, sys.stderr 
sys.stdout = sys.stderr = fh 
# the code you're importing or printing from 
# to restore the defaults. 
sys.stdout = stdout_ 
sys.stderr = stderr_ 
1

除了重定向標準錯誤輸出,不要忘記關閉文件寫入到它後正常。如果您不這樣做,則輸出可能無法正確同步,並且文件末尾可能會丟失。 Python的with結構非常適合這些情況:

with open('thefile.txt', 'w') as f: 
    # do the magic here 
    pass 
相關問題