Alexey Nezhdanov <snakeru@gmail.com> writes:
The most essential for me is freeing all sorts of RAM that python allocated for objects or whatever else.
Reinitializing Python should work, but it might not produce the effect you expect.
Python allocates memory using the underlying C functions such as malloc. Shutting down the interpreter simply makes Python call free on the memory segments that belong to Python objects. Because of the way malloc and free work, doing that is no guarantee that memory will be returned to the operating system. free() only guarantees that the memory will be marked as usable for unspecified later calls to malloc. Some malloc implementations go one step further and actually return the memory to the system, but that is only possible when freeing the block(s) at the very end of the region, so you cannot rely on it.
At the end of the day, your process will probably not decrease in memory footprint; however, it will not grow on further allocations because it will reuse the freed memory. But, barring a bug in Python, that is exactly the situation you would be in if you didn't reinitialize the interpreter in the first place.
IOW - I want python to be returned in virgin state as it was on my program load w/o exiting my program and closing all files/tcp connections that it have opened/or resetting any of other my C data structures that were created.
Doesn't Python automatically close open files when the script finishes?