2

Say I had a Python file, 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.

5 Answers 5

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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 """
2

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
$ 

1 Comment

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!
1

python -i or the code module.

Comments

1

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.

1 Comment

Note that importing in the REPL is not quite the same, due to the slight difference in what makes up the __main__ module.
0

you can also set PYTHONINSPECT in your environment

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.