How to run Python top level/interpreter with file input?
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 开发者_如何学JAVAbe able to continue with i = 5
.
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
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
$
python -i
or the code
module.
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.
you can also set PYTHONINSPECT
in your environment
精彩评论