擅长:python、mysql、java
<p>您不能仅仅用Python代码来重置Python解释器的状态,尽管您可以用嵌入Python解释器的自定义C程序来重置。你知道吗</p>
<p>然而,对于您的特殊情况,在子解释器中运行您的每个“问题”可能就足够了,类似这样的东西。。。你知道吗</p>
<pre><code>import sys
import code
def reset():
raise SystemExit(123)
sys.modules['__builtin__'].reset = reset
banner = None
while 1:
try:
code.interact(banner=banner, local={})
break
except SystemExit as e:
if e.code == 123:
banner = 'Resetting...'
continue
raise
</code></pre>
<p>…然后当你运行脚本时,你可以这样使用它。。。你知道吗</p>
<pre><code>Python 2.7.4 (default, Apr 19 2013, 18:28:01)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> dir()
['__builtins__']
>>> a = 1
>>> dir()
['__builtins__', 'a']
>>> reset()
Resetting...
>>> dir()
['__builtins__']
</code></pre>