开发者

Is there a way to restart or reset the python interpreter within a python doctest?

I am writing a short tutorial, and would like to be able to run the examples therein using python's doctest using

python -m doctest foo.txt

There is a point in the tutorial at which I want to start using a new, clean python interprete开发者_如何学Pythonr. Is there a mechanism for doing this?


You can use the code module to create a new interpreter. You can even copy global/local variables.

There is a nice example within the Blender documentation here

They advise the following:

In the middle of a script you may want to inspect variables, run functions and inspect the flow.

import code
code.interact(local=locals())

If you want to access both global and local variables run this:

import code
namespace = globals().copy()
namespace.update(locals())
code.interact(local=namespace)

The next example is an equivalent single line version of the script above which is easier to paste into your code:

__import__('code').interact(local=dict(globals(), **locals()))

code.interact can be added at any line in the script and will pause the script to launch an interactive interpreter in the terminal, when you’re done you can quit the interpreter and the script will continue execution.


If all you want is to start a new python interpreter inside the python interpreter you can just issue the command: os.system('python')

Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> import os
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'os']
>>> os.system('python')
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> quit()
0
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'os']
>>>

if however, you want to restart or reset python interpreter and not start a new python interpreter like above you could look at this solution. I haven't explored it but should help you get started of.

Restarting a Python Interpreter Quietly


To execute a file in IDLE, simply press the F5 key on your keyboard. You can also select Run → Run Module from the menu bar. Either option will restart the Python interpreter and then run the code that you've written with a fresh interpreter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜