0

我的程序很大,我希望记录它的所有打印语句,因此我实现了

F = open('testy.txt','w')
sys.stdout = F

if app.button_press() == True and app.return_data():
    data = app.return_data()
    main(data[0],data[1],data[2],data[3],data[4],data[5],data[6],data[7],data[8])

F.close()

这就是我过去对带有一些打印语句的小程序所做的事情,但是我猜这个程序有几百个,当我运行我的程序时它会冻结我认为它有很多打印语句并且发生内存溢出因此怎么可能我将所有打印语句记录到 .txt 文件中而不影响它的功能?

4

1 回答 1

2

You shouldn't be using print statements for logging, nor should you be redirecting standard out (or any other standard stream) in production code. Rather, you should be using the logging module to write messages, and setting up whatever handlers, probably a file handler or rotating file handler in your case, that you need to record your log messages to the right place.

If you already have too much existing code printing log messages to refactor in one sitting, I'd suggest implementing logging, using it for all logging going forward, setting up a file-like object that shunts standard out to logging to capture existing log messages, then refactoring out all your print-based logging over time.

于 2013-08-27T17:38:13.600 回答