有没有办法在 python doctest 中重新启动或重置 python 解释器?

问题描述 投票:0回答:3

我正在编写一个简短的教程,并且希望能够使用 python 的 doctest 来运行其中的示例

python -m doctest foo.txt

本教程中的某个时刻我想开始使用一个新的、干净的 python 解释器。有没有一个机制可以做到这一点?

python terminal doctest
3个回答
0
投票

您可以使用代码模块来创建新的解释器。您甚至可以复制全局/局部变量。

Blender 文档中有一个很好的示例这里

他们提出以下建议:

在脚本中间,您可能想要检查变量、运行函数并检查流程。

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

如果您想访问全局变量和局部变量,请运行以下命令:

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

下一个示例是上面脚本的等效单行版本,它更容易粘贴到您的代码中:

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

code.interact 可以添加在脚本中的任何行,并将暂停脚本以在终端中启动交互式解释器,完成后您可以退出解释器,脚本将继续执行。


-1
投票

如果您只想在 python 解释器中启动一个新的 python 解释器,您只需发出命令: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']
>>>

但是,如果您想重新启动或重置 python 解释器,而不是像上面那样启动新的 python 解释器,您可以查看此解决方案。我还没有探索过,但应该可以帮助你开始。

安静地重新启动Python解释器


-3
投票

要在 IDLE 中执行文件,只需按键盘上的 F5 键即可。您还可以从菜单栏中选择“运行”→“运行模块”。任一选项都会重新启动 Python 解释器,然后运行您使用新解释器编写的代码。

© www.soinside.com 2019 - 2024. All rights reserved.