with open('filename.py', 'r') as f: exec(f.read())

Yup, that’s it. I probably type this Python pattern more than any other when I’m prototyping.

I used to use JetBrains as my IDE (thank you Student License from UMich) and there was a configuration for Python scripts to be executed in an interactive Python session instead of in batch. I have long switched to VSCode (like a sane person), so the IDE-agnostic (or even IDE-independent) replacement for this interactive session feature is the above code.

This pattern lets you quickly develop and run code simultaneously and maintain session variables as you develop, similar to how the MATLAB IDE works. Also, if the script being ideated has a particular codeblock with long execution time that does not need to be rerun, you can comment out that code before running the script again for your changes to refresh the session variables without a long runtime.

Leave a Reply