BadFileDescriptor
錯誤和相應的內存訪問衝突是由窗口模式下的應用程序的stdout
是固定大小的緩衝區引起的。 因此,如果您直接致電stdout
,或者直接與print
或sys.stdout
聯繫,那麼經過一段時間後,您會看到這些錯誤。
你可以解決這個問題:
- 刪除/上
stdout
- 註釋掉的著作使用
logging
,而不是打印到stdout
- 在應用程序的開始執行重定向
stdout
。這是需要更少代碼的解決方案,儘管我認爲將調試語句移到logging
將是更好的選擇。只是執行程序之前 import sys
import tempfile
sys.stdout = tempfile.TemporaryFile()
sys.stderr = tempfile.TemporaryFile()
:
重定向stdout
你可以使用這種代碼。你也可以使用一些自定義對象將輸出放在「日誌」文件或其他內容中,重要的是輸出不應該填充固定大小的緩衝區。
例如,你可以做這樣的事情,以便能夠利用logging
模塊,無需改變太多代碼:
import sys
import logging
debug_logger = logging.getLogger('debug')
debug_logger.write = debug_logger.debug #consider all prints as debug information
debug_logger.flush = lambda: None # this may be called when printing
#debug_logger.setLevel(logging.DEBUG) #activate debug logger output
sys.stdout = debug_logger
這種方法的缺點是print
執行多次調用stdout.write
每個行:
>>> print 'test'
DEBUG:debug:test
DEBUG:debug:
如果你想你大概能避免這種行爲寫一個真正write
功能,只有與調用the_logger.debug
「全線」。
無論如何,我認爲這種解決方案應該只是暫時的,並且只能在將print
移植到logging.debug
之前使用。
(顯然伐木者應該寫入一個文件,而不是stdout
,以避免錯誤。)
請問您的程序中使用'print'陳述或者'sys.stdout.write'?閱讀[這裏](https://groups.google.com/forum/?fromgroups=#!topic/it.comp.lang.python/3770608EYPc)(意大利語對你不幸),錯誤的文件描述符錯誤可能是由於,你可以解決它刪除/註釋'print's或重定向'sys.stdout'或使用'logging'來代替。 看來,當你以窗口模式啓動應用程序時,它的'stdout'是一個固定大小的緩衝區,這會導致內存訪問衝突。 – Bakuriu
它確實使用打印語句。你能告訴我更多關於如何重定向sys.stdout嗎?我的意思是,是否可以用一行代碼輕鬆替換軟件中的所有打印語句? –
你可以放置類似'import sys;導入tempfile; sys.stdout = tempfile.TemporaryFile(); sys.stderr = tempfile.TemporaryFile()'(希望有更好的格式化)在程序執行的最初階段,所有'print's將被重定向到一個臨時文件,當你的程序退出時它將被刪除。對於更長期的解決方案,我會考慮使用'logging'。 – Bakuriu