【问题标题】:Is there a way to restart or reset the python interpreter within a python doctest?有没有办法在 python doctest 中重新启动或重置 python 解释器?
【发布时间】:2011-08-23 13:02:49
【问题描述】:

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

python -m doctest foo.txt

教程中有一点我想开始使用一个新的、干净的 python 解释器。有这样做的机制吗?

【问题讨论】:

    标签: python doctest


    【解决方案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 解释器,您可以查看此解决方案。我还没有探索过,但应该可以帮助您入门。

    Restarting a Python Interpreter Quietly

    【讨论】:

    • 聪明,但它在 doctest 中不起作用:当孩子开始时,它等待来自标准输入的输入。我需要探索 doctest 如何处理标准输入和标准输出,以查看与 popen 相关的解决方案是否可行...
    • 引用的“安静地重新启动 Python 解释器”应用程序使用 savestate 配方并不会真正重置状态,例如它不会取消定义任何交互定义的函数。
    猜你喜欢
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 2018-03-10
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 2022-12-05
    相关资源
    最近更新 更多