views:

49

answers:

5

I've always wondered how to do this, it's useful for manual unit testing of individual python scrips. Say I had a python file that did something, and I wanted to run it in the top level, but after it finishes, I want to pick up where it leaves off. I want to be able to use the objects it creates, etc.

A simple example, let's say I have a python script that does i = 5. When the script ends, I want to be returned to the top level and be able to continue with i = 5.

+1  A: 

python -i or the code module.

Ignacio Vazquez-Abrams
+4  A: 

Assuming I'm understanding your question correctly, the -i switch is what you're looking for:

~$ echo "i = 5" > start.py
~$ python -i start.py 
>>> i
5
Epcylon
Thanks! I'm embarrassed to say that I don't know this after writing about a year worth of python. Is this in the python docs somewhere? I could not find it for the life of me.
Kevin
`python -h` shows, among other things, """-i : inspect interactively after running script; forces a prompt even if stdin does not appear to be a terminal; also PYTHONINSPECT=x"""
Alex Martelli
A: 

you can also set PYTHONINSPECT in your environment

gnibbler
+1  A: 

As mentioned, 'python -i ' is the closest answer to your question. You can also use 'import' to run scripts in the interpreter. For example, if you're editing "testscript.py" you could do:

$ ls -l
-rw-r--r-- 1 Xxxx None    771 2009-02-07 18:26 testscript.py
$ python
>>> import testscript
>>> print testlist
['result1', 'result2']
>>>

testscript.py has to be in sys.path for this to work (sys.path includes the current working directory automatically).

This is useful if you want to run a few different scripts and have the environment from all of them at the same time.

Goladus
Note that importing in the REPL is not *quite* the same, due to the slight difference in what makes up the `__main__` module.
Ignacio Vazquez-Abrams
+2  A: 

Looks like you're looking for execfile - for example:

$ cat >seti.py
i = 5
^C
$ cat >useit.py
execfile('seti.py')
print i
$ python useit.py 
5
$ 
Alex Martelli
This is actually useful as well, I used to execute other python files using sys calls, and couldn't find on google how to do this either. Thanks!
Kevin