简体   繁体   English

在Python中清除终端窗口,内存/性能

[英]Clearing the terminal window in Python, memory/performance

I'm using a script that runs for many hours, which prints statements to verify whether or not issues might have arisen (data is downloaded from the web, which sometimes gets distorted). 我正在使用一个运行多个小时的脚本,该脚本会打印语句以验证是否可能出现问题(数据是从Web下载的,有时会失真)。

I've noticed a significant drop in performance after a while. 我注意到一段时间后性能显着下降。 I suspect that the many thousands of lines of print statements might be the reason. 我怀疑可能是成千上万行打印语句的原因。

It is commonly known that the terminal can be cleared of these print statements by the following line of code: 众所周知,可以通过以下代码行清除终端的这些打印语句:

import os
os.system('cls') # for windows

Still, I suspect that this doesn't actually improve the performance speed and that it's merely a perceived improvement due to the fact that the screen is cleared. 尽管如此,我怀疑这实际上并没有提高性能速度,并且由于清除了屏幕的事实,这仅仅是可以感知的改进。 Is that true or not? 那是真的吗?

I've also considered suppressing certain print statements with the following code: 我还考虑过使用以下代码禁止某些打印语句:

import sys
class NullWriter(object):
 def write(self, arg):
  pass
nullwrite = NullWriter()
oldstdout = sys.stdout
sys.stdout = oldstdout # enable output 
print("text that I want to see")
sys.stdout = nullwrite # disable output
print("text I don't want to see")

My question: How can I improve the performance (speed) of my script, given that I still want to see the most recent print statements? 我的问题:考虑到我仍想查看最新的打印语句,如何提高脚本的性能(速度)?

If you like you can just do a line feed without a carriage return and override the last line: 如果您愿意,可以不使用回车符而换行并覆盖最后一行:

sys.stdout.write("\rDoing things")
sys.stdout.flush()

Printing over time shouldn't use any extra memory within python, but you might have your terminal's buffer set to high which can use a lot of memory. 随着时间的推移,打印不应该在python中使用任何额外的内存,但是您可能会将终端的缓冲区设置为高,这会占用大量内存。 Or it's just taking time to flush the buffer because you're writing so fast to stdout. 否则,清空缓冲区只是花时间,因为您写stdout的速度如此之快。

You can also use the print function 您也可以使用打印功能

Python 2.6+ Python 2.6以上

From Python 2.6 you can import the print function from Python 3: 在Python 2.6中,您可以从Python 3中导入打印功能:

from __future__ import print_function

This allows you to use the Python 3 solution below. 这使您可以使用下面的Python 3解决方案。

Python 3 Python 3

In Python 3, the print statement has been changed into a function. 在Python 3中,将print语句更改为一个函数。 In Python 3, you can instead do: 在Python 3中,您可以改为:

print('.', end='')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM