tags:

views:

56

answers:

2

Heyo,

Just started writing an assembler for the imaginary computer my class is creating wire-by-wire since the one the TA's provided sucks hard. I chose python even though I've never really used it that much (but know the basic syntax) and am loving it.

My favorite ability is how I can take a method I just wrote, paste it into the shell and then unit test it by hand (I'm using IDLE).

I'm just wondering if there is a way to expose all the symbols in my python code to the shell automatically, so I can debug without copying and pasting my code into the shell every time (especially when I make a modification in the code).

Cheers

+1  A: 

you can import the module that your code is in. This will expose all of the symbols prefixed with the module name.

The details for the easiest way to do it depend on your operating system but you can always do:

>>> sys.path.append('/path/to/directory/that/my/module/is/in/')
>>> import mymod #.py

later after you make a change, you can just do

>>>> reload(mymod)

and the symbols will now reference the new values. Note that from mymod import foo will break reload in the sense that foo will not be updated after a call to reload. So just use mymod.foo.

Essentially the trick is to get the directory containing the file on your PYTHONPATH environment variable. You can do this from .bashrc on linux for example. I don't know how to go about doing it on another operating system. I use virualenv with has a nice wrapper and workon command so I just have to type workon foo and it runs shell scripts (that I had to write) that add the necessary directories to my python path.

When I was just starting off though, I made one permanent addition to my PYTHONPATH env variable and kept module I wrote in there.

Another alternative is to execute your module with the -i option.

$ python -i mymod.py

This will execute the module through to completion and then leave you at the interpreter. this isn't IDLE though, it's a little rougher but you are now in your module's namespace (or rather the module's namespace is the global namespace)

aaronasterling
module being source file?
Lanissum
@Lanissum. correct. if your sourcefile is 'mymod.py', then `import mymod`
aaronasterling
@excellent, thanks a bunch!
Lanissum
A: 

Check IPython. It's enhanced interactive Python shell. You can %run your script and it will automatically expose all your global objects to the shell. It's very easy to use and powerful. You can even debug your code using it.

For example, if your script is:

import numpy as np
def f(x):
    return x + 1

You can do the following:

%run yourScript.py
x = np.eye(4)
y = f(x)
Yassin