Start a global IPython shell, which we need for IPython-specific syntax.
()
| 70 | |
| 71 | |
| 72 | def start_ipython(): |
| 73 | """Start a global IPython shell, which we need for IPython-specific syntax. |
| 74 | """ |
| 75 | global get_ipython |
| 76 | |
| 77 | # This function should only ever run once! |
| 78 | if hasattr(start_ipython, 'already_called'): |
| 79 | return |
| 80 | start_ipython.already_called = True |
| 81 | |
| 82 | # Store certain global objects that IPython modifies |
| 83 | _displayhook = sys.displayhook |
| 84 | _excepthook = sys.excepthook |
| 85 | _main = sys.modules.get('__main__') |
| 86 | |
| 87 | # Create custom argv and namespaces for our IPython to be test-friendly |
| 88 | config = tools.default_config() |
| 89 | config.TerminalInteractiveShell.simple_prompt = True |
| 90 | |
| 91 | # Create and initialize our test-friendly IPython instance. |
| 92 | shell = TerminalInteractiveShell.instance(config=config, |
| 93 | ) |
| 94 | |
| 95 | # A few more tweaks needed for playing nicely with doctests... |
| 96 | |
| 97 | # remove history file |
| 98 | shell.tempfiles.append(config.HistoryManager.hist_file) |
| 99 | |
| 100 | # These traps are normally only active for interactive use, set them |
| 101 | # permanently since we'll be mocking interactive sessions. |
| 102 | shell.builtin_trap.activate() |
| 103 | |
| 104 | # Modify the IPython system call with one that uses getoutput, so that we |
| 105 | # can capture subcommands and print them to Python's stdout, otherwise the |
| 106 | # doctest machinery would miss them. |
| 107 | shell.system = types.MethodType(xsys, shell) |
| 108 | |
| 109 | shell._showtraceback = types.MethodType(_showtraceback, shell) |
| 110 | |
| 111 | # IPython is ready, now clean up some global state... |
| 112 | |
| 113 | # Deactivate the various python system hooks added by ipython for |
| 114 | # interactive convenience so we don't confuse the doctest system |
| 115 | sys.modules['__main__'] = _main |
| 116 | sys.displayhook = _displayhook |
| 117 | sys.excepthook = _excepthook |
| 118 | |
| 119 | # So that ipython magics and aliases can be doctested (they work by making |
| 120 | # a call into a global _ip object). Also make the top-level get_ipython |
| 121 | # now return this without recursively calling here again. |
| 122 | _ip = shell |
| 123 | get_ipython = _ip.get_ipython |
| 124 | builtin_mod._ip = _ip |
| 125 | builtin_mod.ip = _ip |
| 126 | builtin_mod.get_ipython = get_ipython |
| 127 | |
| 128 | # Override paging, so we don't require user interaction during the tests. |
| 129 | def nopage(strng, start=0, screen_lines=0, pager_cmd=None): |