mrKelley
mrKelley

Reputation: 3524

Leave Variables in Memory After Execution

In Matlab, when you run a script, variables stick around in memory and you have access in the shell. I find this really useful for debugging and exploring. I'm trying to achieve a similar effect in Python. Maybe this is not even possible.

As an example, suppose I have a file named script.py

#!/usr/bin/env python

def foo(n):
    return 2*n

x = 5
y = foo(5)

I want to be able to run this and have access to x and y in a python shell. I tried >>> import script which gives me access to foo via script.foo(), but I want access to x and y too.

>>> from script import * does not get the job done either.

How do I make python leave these (in memory) in a python shell for me?

Upvotes: 0

Views: 158

Answers (2)

Marius
Marius

Reputation: 60070

The simplest way to achieve this is by running your script with the -i flag (which stands for "inspect interactively").

python -i my_script.py

The script will run and then the Python shell prompt >>> will be shown, allowing you to interact with the variables that the script created.

Another good option would be to install IPython, which adds some extra features to the basic Python shell. Within an IPython session, you can call

%run my_script.py

to get the same effect. IPython should be available in your Linux distro's repositories.

Upvotes: 5

mhlester
mhlester

Reputation: 23231

You can use the pdb module to enter the debugger at any particular point. For instance:

import pdb

def foo(n):
    pdb.set_trace()  # <-- enters debugger here
    return 2*n

x = 5
y = foo(5)

Upvotes: 1

Related Questions