Memory leak when running python in Mac OS Terminal

2019-07-20 09:24发布

问题:

I just ran a python program in the Mac OS Terminal, and there is unusual memory leak.

The program is simple like this:

for i in xrange(1000000000, 2000000000, 10):
  i2 = i * i
  print i, i2, str(i2)[::2]
  if str(i2)[::2] == '1234567890':
    break

When the program is running, it consumes more and more memory till it use up all my memory. When I terminate the program, my Terminal.app still consumes a lot of memory, so I guess it's a bug in Terminal.app?

Does anyone have similar experience?

回答1:

This isn't a bug; it's actually a feature. Terminal.app, like many other terminal emulators, saves recent output in a buffer so that you can scroll back (with page up or the scroll bar). You can limit how large this is by going to Terminal -> Preferences -> Settings and setting the scrollback limit to something other than Unlimited.



回答2:

It's not Python that is leaking memory. Look closer. On my machine, the Python process remains at a quiet, stable 3.5 MB of memory.

The memory usage increment you see is most likely due to the Terminal not ever discarding output. You can alter this behavior going to Preferences, Settings, and setting the maximum line number to something else than "Unlimited".