This question comes from the recent question \"Correct way to cap Mathematica memory use?\"
I wonder, is it possible to programmatically restart MathKernel keeping the c
You can programmatically terminate the kernel using Exit[]
. The front end (notebook) will automatically start a new kernel when you next try to evaluate an expression.
Preserving "some code from the previous kernel" is going to be more difficult. You have to decide what you want to preserve. If you think you want to preserve everything, then there's no point in restarting the kernel. If you know what definitions you want to save, you can use DumpSave
to write them to a file before terminating the kernel, and then use <<
to load that file into the new kernel.
On the other hand, if you know what definitions are taking up too much memory, you can use Unset
, Clear
, ClearAll
, or Remove
to remove those definitions. You can also set $HistoryLength to something smaller than Infinity
(the default) if that's where your memory is going.