代码之家  ›  专栏  ›  技术社区  ›  Gattster

如何在运行的doctest中使用ipython的ipshell嵌入

  •  3
  • Gattster  · 技术社区  · 15 年前

    请帮助我在doctest中运行嵌入式ipython控制台。示例代码演示了该问题,并将挂起您的终端。在bashshell上,我键入ctrl-Z,然后杀死%1,以突破并杀死,因为ctrl-C不起作用。

    def some_function():
        """
        >>> some_function()
        'someoutput'
        """
        # now try to drop into an ipython shell to help 
        # with development
        import IPython.Shell; IPython.Shell.IPShellEmbed(argv=[])()
        return 'someoutput'
    
    if __name__ == '__main__':
        import doctest
        print "Running doctest . . ."
        doctest.testmod()
    

    IPython.Shell.IPShellEmbed . 这个技巧在我尝试过的任何地方都有效(在django manage.py运行服务器、单元测试中),但在doctests中不起作用。我认为这与doctest控制stdin/stdout有关。

    -菲利浦

    1 回复  |  直到 15 年前
        1
  •  0
  •   Gattster    15 年前

    我给ipython用户组发了电子邮件,得到了一些帮助。现在有一个 support ticket 在未来版本的ipython中修复此功能。下面是一段代码片段,其中包含一个解决方法:

    import sys
    
    from IPython.Shell import IPShellEmbed
    
    class IPShellDoctest(IPShellEmbed):
       def __call__(self, *a, **kw):
           sys_stdout_saved = sys.stdout
           sys.stdout = sys.stderr
           try:
               IPShellEmbed.__call__(self, *a, **kw)
           finally:
               sys.stdout = sys_stdout_saved
    
    
    def some_function():
      """
      >>> some_function()
      'someoutput'
      """
      # now try to drop into an ipython shell to help
      # with development
      IPShellDoctest()(local_ns=locals())
      return 'someoutput'
    
    if __name__ == '__main__':
      import doctest
      print "Running doctest . . ."
      doctest.testmod()