Search code examples
pythonenthoughtcanopy

Run script in interactive namespace from within Canopy


From within the Canopy editor, how do I run a python script within the current interactive namespace?

Specifically, I have a large model object that takes a long time to load. I would like to instantiate the model in the interactive shell and then be able to run scripts that operate on the existing model. If I select the text in my script and click the "Run the selected text" button, everything works fine. Alternatively, if I type "run -i script.py" as suggested in this related question it also works fine. However, if I click the "Run the current file" button, the script appears to run in a clean namespace and cannot find any of the variables that already exist in the interactive shell.

This is the specific code that I am trying to use to only load the model on the first pass through the script.

# Only instantiating the model object if it does not already exist
if 'model' not in locals():
    model = TreeModel(filename)

Solution

  • Click "Run the current file", then when it fails to run as desired, press the up arrow to recall the run command, insert the -i, and press Enter to re-run in ipython's interactive mode.

    In theory, Canopy could be provided with this as yet another Run variant, but we want to avoid cluttering the UI with seldom-used options.