Python console : how to do these special tasks?

  1. While testing things, we may get trapped with variables previously declared and assigned in the Python console. I’m looking for a way to completely clear/clean/reset the Python console to avoid the need of restarting Slicer.

slicer.app.pythonConsole().reset() does not work as expected, previous declared variables persist.

  1. How can we load/run a Python script saved on disk ? Something like ‘source’ in bash.

Thanks for any advice.

When I’m just experimenting, I’ll often make a script like this that conditionally initializes some bulk data (e.g. downloading a sample volume) if the node is not found and leaves the intermediate values in the python console for interactive query and also to test invoking methods.

Then I use a command like this:

path="c:/pieper/facenav/facenav.py"
exec(open(path).read())

to load the script which works like source in bash. It can typically just be re-run dozens of times while refining the logic. Then sometimes if the logic is wrong you may need to re-start Slicer but it just means the initialization needs to run again.

1 Like

This works very well, thank you.