4

At the end of my program, where nothing really needs to happen, the CPython 3.2 interpreter spends almost 2 minutes doing garbage collection. It is a known issue.

Luckily, in my case, I don't need to do any garbage collection until the end of the program. Therefore, I just need to find a way to exit the program when it's done, without giving gc.collect() a chance to run.

Pressing 'CTRL+C' on Windows seems to do it. I suppose I could also find the process id of the python interpreter, and kill it using an OS call.

Is there a way to achieve the same effect using pure Python (perhaps an exception or a standard library call), hopefully platform-independent?

Community
  • 1
  • 1
max
  • 49,282
  • 56
  • 208
  • 355

1 Answers1

7
import os
os._exit(0)

This is discouraged because destructors could perform some useful action. If you're sure you don't need those destructors to run, this should work.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • This is perfect. What types of things should I be aware of when using this? I hope file handles and network connections would still be released by the OS, even if their destructors don't run? – max Jan 08 '13 at 03:50
  • 2
    @max: The operating system *should* be able to perform cleanup of system resources. What you may want to be more worried about is application stuff. For example, if your application is trying to perform some sort of multi-step file operation and you cut it off in the middle, the file might not be in a consistent state. – icktoofay Jan 08 '13 at 03:55
  • 1
    Routines registered with `atexit` (either by you or a library you're using) will not run when you use `_exit`. – James Henstridge Jan 08 '13 at 04:23
  • 2
    Oh, and I just read in the docs that `stdio` buffers will not be flushed. As long as I'm aware of that, it's easy to deal with. – max Jan 08 '13 at 09:37
  • Warning, this also skips flushing stdout. I was having a heck of a time figuring out why my script was writing to the terminal fine but not when redirected to a file or piped to another program... – Thomas Andrews Jan 23 '22 at 19:12