def get_ipython():
    from IPython.terminal.interactiveshell import TerminalInteractiveShell
    if TerminalInteractiveShell._instance:
        return TerminalInteractiveShell.instance()

    config = tools.default_config()
    config.TerminalInteractiveShell.simple_prompt = True

    # Create and initialize our test-friendly IPython instance.
    shell = TerminalInteractiveShell.instance(config=config)
    return shell
Пример #2
0
def main(no_quickstart):
    """Use quickstart to ensure we have correct env, then execute imports in ipython and done."""
    if not no_quickstart:
        from cfme.scripting import quickstart

        quickstart.main(quickstart.args_for_current_venv())
    print('Welcome to IPython designed for running CFME QE code.')
    ipython = TerminalInteractiveShell.instance()
    for code_import in IMPORTS:
        print('> {}'.format(code_import))
        ipython.run_cell(code_import)
    from cfme.utils.path import conf_path
    custom_import_path = conf_path.join('miq_python_startup.py')
    if custom_import_path.exists():
        with open(custom_import_path.strpath, 'r') as custom_import_file:
            custom_import_code = custom_import_file.read()
        print('Importing custom code:\n{}'.format(custom_import_code.strip()))
        ipython.run_cell(custom_import_code)
    else:
        print(
            'You can create your own python file with imports you use frequently. '
            'Just create a conf/miq_python_startup.py file in your repo. '
            'This file can contain arbitrary python code that is executed in this context.'
        )
    ipython.interact()
Пример #3
0
    def __init__(self, color_scheme=None, completekey=None, stdin=None, stdout=None, context=5):

        # Parent constructor:
        try:
            self.context = int(context)
            if self.context <= 0:
                raise ValueError("Context must be a positive integer")
        except (TypeError, ValueError):
            raise ValueError("Context must be a positive integer")

        OldPdb.__init__(self, completekey, stdin, stdout)

        # IPython changes...
        self.shell = get_ipython()

        if self.shell is None:
            # No IPython instance running, we must create one
            from IPython.terminal.interactiveshell import TerminalInteractiveShell

            self.shell = TerminalInteractiveShell.instance()

        if color_scheme is not None:
            warnings.warn("The `color_scheme` argument is deprecated since version 5.1", DeprecationWarning)
        else:
            color_scheme = self.shell.colors

        self.aliases = {}

        # Create color table: we copy the default one from the traceback
        # module and add a few attributes needed for debugging
        self.color_scheme_table = exception_colors()

        # shorthands
        C = coloransi.TermColors
        cst = self.color_scheme_table

        cst["NoColor"].colors.prompt = C.NoColor
        cst["NoColor"].colors.breakpoint_enabled = C.NoColor
        cst["NoColor"].colors.breakpoint_disabled = C.NoColor

        cst["Linux"].colors.prompt = C.Green
        cst["Linux"].colors.breakpoint_enabled = C.LightRed
        cst["Linux"].colors.breakpoint_disabled = C.Red

        cst["LightBG"].colors.prompt = C.Blue
        cst["LightBG"].colors.breakpoint_enabled = C.LightRed
        cst["LightBG"].colors.breakpoint_disabled = C.Red

        cst["Neutral"].colors.prompt = C.Blue
        cst["Neutral"].colors.breakpoint_enabled = C.LightRed
        cst["Neutral"].colors.breakpoint_disabled = C.Red

        self.set_colors(color_scheme)

        # Add a python parser so we can syntax highlight source while
        # debugging.
        self.parser = PyColorize.Parser()

        # Set the prompt - the default prompt is '(Pdb)'
        self.prompt = prompt
Пример #4
0
def run_ipython_shell_v11(locals, globals, first_time):
    '''IPython shell from IPython version 0.11'''
    if first_time:
        banner = "Hit Ctrl-D to return to PuDB."
    else:
        banner = ""

    try:
        # IPython 1.0 got rid of the frontend intermediary, and complains with
        # a deprecated warning when you use it.
        from IPython.terminal.interactiveshell import TerminalInteractiveShell
        from IPython.terminal.ipapp import load_default_config
    except ImportError:
        from IPython.frontend.terminal.interactiveshell import \
                TerminalInteractiveShell
        from IPython.frontend.terminal.ipapp import load_default_config
    # XXX: in the future it could be useful to load a 'pudb' config for the
    # user (if it exists) that could contain the user's macros and other
    # niceities.
    config = load_default_config()
    shell = TerminalInteractiveShell.instance(config=config, banner2=banner)
    # XXX This avoids a warning about not having unique session/line numbers.
    # See the HistoryManager.writeout_cache method in IPython.core.history.
    shell.history_manager.new_session()
    # Save the originating namespace
    old_locals = shell.user_ns
    old_globals = shell.user_global_ns
    # Update shell with current namespace
    _update_ns(shell, locals, globals)
    shell.mainloop(banner)
    # Restore originating namespace
    _update_ns(shell, old_locals, old_globals)
Пример #5
0
def main(obj):
    click.echo("Welcome to IPython designed for running RHAMT code.")
    ipython = TerminalInteractiveShell.instance()

    for code_import in IMPORTS:
        click.echo(f"> {code_import}")
        ipython.run_cell(code_import)

    # create default app
    ipython.run_cell("app = Application()")
    click.echo("> app = $magic Application")

    from rhamt.utils.path import CONF_PATH

    custom_import_path = CONF_PATH / "rhmt_shell_startup.py"

    if custom_import_path.exists():
        with open(custom_import_path, "r") as custom_import_file:
            custom_import_code = custom_import_file.read()
        click.echo(f"Importing custom code:\n{custom_import_code.strip()}")
        ipython.run_cell(custom_import_code)
    else:
        click.echo(
            "You can create your own python file with imports you use frequently. "
            "Just create a conf/rhmt_shell_startup.py file in your repo. "
            "This file can contain arbitrary python code that is executed in this context."
        )
    ipython.interact()
Пример #6
0
def run_ipython_shell_v11(locals, globals, first_time):
    '''IPython shell from IPython version 0.11'''
    if first_time:
        banner = "Hit Ctrl-D to return to PuDB."
    else:
        banner = ""

    try:
        # IPython 1.0 got rid of the frontend intermediary, and complains with
        # a deprecated warning when you use it.
        from IPython.terminal.interactiveshell import TerminalInteractiveShell
        from IPython.terminal.ipapp import load_default_config
    except ImportError:
        from IPython.frontend.terminal.interactiveshell import \
                TerminalInteractiveShell
        from IPython.frontend.terminal.ipapp import load_default_config
    # XXX: in the future it could be useful to load a 'pudb' config for the
    # user (if it exists) that could contain the user's macros and other
    # niceities.
    config = load_default_config()
    shell = TerminalInteractiveShell.instance(config=config,
            banner2=banner)
    # XXX This avoids a warning about not having unique session/line numbers.
    # See the HistoryManager.writeout_cache method in IPython.core.history.
    shell.history_manager.new_session()
    # Save the originating namespace
    old_locals = shell.user_ns
    old_globals = shell.user_global_ns
    # Update shell with current namespace
    _update_ns(shell, locals, globals)
    shell.mainloop(banner)
    # Restore originating namespace
    _update_ns(shell, old_locals, old_globals)
Пример #7
0
def main():
    """Use quickstart to ensure we have correct env, then execute imports in ipython and done."""
    quickstart.main(
        quickstart.parser.parse_args(['--mk-virtualenv', sys.prefix]))
    print('Welcome to IPython designed for running CFME QE code.')
    ipython = TerminalInteractiveShell.instance()
    from cfme.utils import appliance
    appliance.CREATE_IS_PEDANTIC = False
    for code_import in IMPORTS:
        print('> {}'.format(code_import))
        ipython.run_cell(code_import)
    from cfme.utils.path import conf_path
    custom_import_path = conf_path.join('miq_python_startup.py')
    if custom_import_path.exists():
        with open(custom_import_path.strpath, 'r') as custom_import_file:
            custom_import_code = custom_import_file.read()
        print('Importing custom code:\n{}'.format(custom_import_code.strip()))
        ipython.run_cell(custom_import_code)
    else:
        print(
            'You can create your own python file with imports you use frequently. '
            'Just create a conf/miq_python_startup.py file in your repo. '
            'This file can contain arbitrary python code that is executed in this context.'
        )
    ipython.interact()
Пример #8
0
        def init_shell(self):
            banner1 = 'Umeng development shell, do whatever you want.\n' if DEVELOP_MODE else \
                'Umeng production shell, use it carefully!\n'
            self.shell = TerminalInteractiveShell.instance(config=self.config,
                                                           display_banner=False, profile_dir=self.profile_dir,
                                                           ipython_dir=self.ipython_dir, banner1=banner1, banner2='')

            self.shell.configurables.append(self)
Пример #9
0
 def _get_shell(self):
     if ipy.get_ipython() is None:
         shell = ipy_shell.instance()
         if shell is None:
             self._create_profile()
             self._get_shell()
         shell.user_ns['shell'] = shell
     return ipy.get_ipython()
Пример #10
0
    def __init__(self,color_scheme='NoColor',completekey=None,
                 stdin=None, stdout=None, context=5):

        # Parent constructor:
        try:
            self.context=int(context)
            if self.context <= 0:
                raise ValueError("Context must be a positive integer")
        except (TypeError, ValueError):
                raise ValueError("Context must be a positive integer")

        OldPdb.__init__(self,completekey,stdin,stdout)

        # IPython changes...
        self.shell = get_ipython()

        if self.shell is None:
            # No IPython instance running, we must create one
            from IPython.terminal.interactiveshell import \
                TerminalInteractiveShell
            self.shell = TerminalInteractiveShell.instance()

        self.aliases = {}

        # Create color table: we copy the default one from the traceback
        # module and add a few attributes needed for debugging
        self.color_scheme_table = exception_colors()

        # shorthands
        C = coloransi.TermColors
        cst = self.color_scheme_table

        cst['NoColor'].colors.prompt = C.NoColor
        cst['NoColor'].colors.breakpoint_enabled = C.NoColor
        cst['NoColor'].colors.breakpoint_disabled = C.NoColor

        cst['Linux'].colors.prompt = C.Green
        cst['Linux'].colors.breakpoint_enabled = C.LightRed
        cst['Linux'].colors.breakpoint_disabled = C.Red

        cst['LightBG'].colors.prompt = C.Blue
        cst['LightBG'].colors.breakpoint_enabled = C.LightRed
        cst['LightBG'].colors.breakpoint_disabled = C.Red

        self.set_colors(color_scheme)

        # Add a python parser so we can syntax highlight source while
        # debugging.
        self.parser = PyColorize.Parser()

        # Set the prompt - the default prompt is '(Pdb)'
        Colors = cst.active_colors
        if color_scheme == 'NoColor':
            self.prompt = prompt
        else:
            # The colour markers are wrapped by bytes 01 and 02 so that readline
            # can calculate the width.
            self.prompt = u'\x01%s\x02%s\x01%s\x02' % (Colors.prompt, prompt, Colors.Normal)
Пример #11
0
 def init_shell(self):
     self.shell = TerminalInteractiveShell.instance(
         config=self.config,
         display_banner=False,
         profile_dir=self.profile_dir,
         ipython_dir=self.ipython_dir,
         banner1=get_banner(),
         banner2='')
     self.shell.configurables.append(self)
Пример #12
0
def main():
    ipython = TerminalInteractiveShell.instance()
    for import_statement in DEFAULT_IMPORTS:
        click.echo(f'> {import_statement}')
        ipython.run_cell(import_statement)
        # This can be improved to read a default conf file location
        # So that users can write their own default imports for their local clone

    ipython.interact()
Пример #13
0
def run():
    shell = TerminalInteractiveShell.instance()
    shell.user_ns['shell'] = shell
    shell.define_macro('x', 'a,b=1,2')
    shell.define_macro('y', 'a,b=3,4')
    shell.config['using'] = True
    a, b = 0, 0
    x, y = shell.user_ns['x'], shell.user_ns['y']
    ipy.embed(display_banner=False, config=shell.config)
Пример #14
0
    def __init__(self,
                 color_scheme='NoColor',
                 completekey=None,
                 stdin=None,
                 stdout=None,
                 context=5):

        # Parent constructor:
        try:
            self.context = int(context)
            if self.context <= 0:
                raise ValueError("Context must be a positive integer")
        except (TypeError, ValueError):
            raise ValueError("Context must be a positive integer")

        OldPdb.__init__(self, completekey, stdin, stdout)

        # IPython changes...
        self.shell = get_ipython()

        if self.shell is None:
            # No IPython instance running, we must create one
            from IPython.terminal.interactiveshell import \
                TerminalInteractiveShell
            self.shell = TerminalInteractiveShell.instance()

        self.aliases = {}

        # Create color table: we copy the default one from the traceback
        # module and add a few attributes needed for debugging
        self.color_scheme_table = exception_colors()

        # shorthands
        C = coloransi.TermColors
        cst = self.color_scheme_table

        cst['NoColor'].colors.prompt = C.NoColor
        cst['NoColor'].colors.breakpoint_enabled = C.NoColor
        cst['NoColor'].colors.breakpoint_disabled = C.NoColor

        cst['Linux'].colors.prompt = C.Green
        cst['Linux'].colors.breakpoint_enabled = C.LightRed
        cst['Linux'].colors.breakpoint_disabled = C.Red

        cst['LightBG'].colors.prompt = C.Blue
        cst['LightBG'].colors.breakpoint_enabled = C.LightRed
        cst['LightBG'].colors.breakpoint_disabled = C.Red

        self.set_colors(color_scheme)

        # Add a python parser so we can syntax highlight source while
        # debugging.
        self.parser = PyColorize.Parser()

        # Set the prompt - the default prompt is '(Pdb)'
        self.prompt = prompt
Пример #15
0
 def init_shell(self):
     self.shell = TerminalInteractiveShell.instance(
         config=self.config,
         display_banner=False,
         profile_dir=self.profile_dir,
         ipython_dir=self.ipython_dir,
         banner1=get_banner(),
         banner2=''
     )
     self.shell.configurables.append(self)
Пример #16
0
 def init_shell(self):
     """initialize the InteractiveShell instance"""
     # Create an InteractiveShell instance.
     # shell.display_banner should always be False for the terminal
     # based app, because we call shell.show_banner() by hand below
     # so the banner shows *before* all extension loading stuff.
     self.shell = TerminalInteractiveShell.instance(parent=self,
                     display_banner=False, profile_dir=self.profile_dir,
                     ipython_dir=self.ipython_dir, user_ns=self.user_ns)
     self.shell.configurables.append(self)
Пример #17
0
 def init_shell(self):
     """initialize the InteractiveShell instance"""
     # Create an InteractiveShell instance.
     # shell.display_banner should always be False for the terminal
     # based app, because we call shell.show_banner() by hand below
     # so the banner shows *before* all extension loading stuff.
     self.shell = TerminalInteractiveShell.instance(parent=self,
                     display_banner=False, profile_dir=self.profile_dir,
                     ipython_dir=self.ipython_dir, user_ns=self.user_ns)
     self.shell.configurables.append(self)
Пример #18
0
 def run(self):
     install.run(self)
     try:
         from IPython.terminal.interactiveshell import TerminalInteractiveShell
         startup_dir = TerminalInteractiveShell.instance().get_ipython(
         ).profile_dir.startup_dir
         copyfile(os.path.join(here, 'ipypandex', '__init__.py'),
                  os.path.join(startup_dir, '90-ipypandex.py'))
     except ModuleNotFoundError:
         raise RuntimeError(
             "ipypandex requires an ipython installation to work")
Пример #19
0
def run_ipython_shell_v11(globals, locals):
    """IPython shell from IPython version 0.11"""
    if SHELL_FIRST_TIME:
        banner = "Hit Ctrl-D to return to PuDB."
        SHELL_FIRST_TIME.pop()
    else:
        banner = ""

    try:
        # IPython 1.0 got rid of the frontend intermediary, and complains with
        # a deprecated warning when you use it.
        from IPython.terminal.interactiveshell import TerminalInteractiveShell
        from IPython.terminal.ipapp import load_default_config
    except ImportError:
        from IPython.frontend.terminal.interactiveshell import \
                TerminalInteractiveShell
        from IPython.frontend.terminal.ipapp import load_default_config
    # XXX: in the future it could be useful to load a 'pudb' config for the
    # user (if it exists) that could contain the user's macros and other
    # niceities.
    config = load_default_config()
    shell = TerminalInteractiveShell.instance(config=config, banner2=banner)
    # XXX This avoids a warning about not having unique session/line numbers.
    # See the HistoryManager.writeout_cache method in IPython.core.history.
    shell.history_manager.new_session()
    # Save the originating namespace
    old_locals = shell.user_ns
    old_globals = shell.user_global_ns

    # Update shell with current namespace
    _update_ipython_ns(shell, globals, locals)

    args = []
    if ipython_version() < (5, 0, 0):
        args.append(banner)
    else:
        print(banner)

    # XXX Quick and dirty way to fix issues with IPython 8.0.0+, introduced
    # by commit 08d54c0e367b535fd88aca5273fd09e5e70d08f8.
    # Setting _atexit_once_called = True will prevent call to
    # IPython.core.interactiveshell.InteractiveShell._atexit_once() from inside
    # IPython.terminal.interactiveshell.TerminalInteractiveShell.mainloop()
    # This allows us to repeatedly re-call mainloop() and the whole
    # run_ipython_shell_v11() function
    shell._atexit_once_called = True
    shell.mainloop(*args)
    del shell._atexit_once_called

    # Restore originating namespace
    _update_ipython_ns(shell, old_globals, old_locals)
Пример #20
0
def uninstall():
    try:
        from IPython.terminal.interactiveshell import TerminalInteractiveShell

        startup_dir = TerminalInteractiveShell.instance().get_ipython(
        ).profile_dir.startup_dir
        script = os.path.join(startup_dir, '90-ipypandex.py')
        if os.path.exists(script):
            os.remove(script)
            print(f"Script {script} removed")
        else:
            print(f"Script {script} already removed")
    except ModuleNotFoundError:
        # All good, ipython is already removed
        print("IPython is already removed from this installation")
Пример #21
0
def main():
    """Use quickstart to ensure we have correct env, then execute imports in ipython and done."""
    quickstart.main(quickstart.parser.parse_args(['--mk-virtualenv', sys.prefix]))
    print('Welcome to IPython designed for running CFME QE code.')
    ipython = TerminalInteractiveShell.instance()
    for code_import in IMPORTS:
        print('> {}'.format(code_import))
        ipython.run_cell(code_import)
    from cfme.utils.path import conf_path
    custom_import_path = conf_path.join('miq_python_startup.py')
    if custom_import_path.exists():
        with open(custom_import_path.strpath, 'r') as custom_import_file:
            custom_import_code = custom_import_file.read()
        print('Importing custom code:\n{}'.format(custom_import_code.strip()))
        ipython.run_cell(custom_import_code)
    else:
        print(
            'You can create your own python file with imports you use frequently. '
            'Just create a conf/miq_python_startup.py file in your repo. '
            'This file can contain arbitrary python code that is executed in this context.')
    ipython.interact()
 def __init__(self, *args, **kwargs):        
     #Initialization based on: from IPython.testing.globalipapp import start_ipython
     
     self._curr_exec_line = 0
     # Store certain global objects that IPython modifies
     _displayhook = sys.displayhook
     _excepthook = sys.excepthook
 
     # Create and initialize our IPython instance.
     shell = TerminalInteractiveShell.instance()
 
     shell.showtraceback = _showtraceback
     # IPython is ready, now clean up some global state...
     
     # Deactivate the various python system hooks added by ipython for
     # interactive convenience so we don't confuse the doctest system
     sys.displayhook = _displayhook
     sys.excepthook = _excepthook
 
     # So that ipython magics and aliases can be doctested (they work by making
     # a call into a global _ip object).  Also make the top-level get_ipython
     # now return this without recursively calling here again.
     get_ipython = shell.get_ipython
     try:
         import __builtin__
     except:
         import builtins as __builtin__
     __builtin__._ip = shell
     __builtin__.get_ipython = get_ipython
     
     # We want to print to stdout/err as usual.
     io.stdout = original_stdout
     io.stderr = original_stderr
 
     
     self._curr_exec_lines = []
     self.ipython = shell
    def __init__(self, *args, **kwargs):
        #Initialization based on: from IPython.testing.globalipapp import start_ipython

        self._curr_exec_line = 0
        # Store certain global objects that IPython modifies
        _displayhook = sys.displayhook
        _excepthook = sys.excepthook

        # Create and initialize our IPython instance.
        shell = TerminalInteractiveShell.instance()

        shell.showtraceback = _showtraceback
        # IPython is ready, now clean up some global state...

        # Deactivate the various python system hooks added by ipython for
        # interactive convenience so we don't confuse the doctest system
        sys.displayhook = _displayhook
        sys.excepthook = _excepthook

        # So that ipython magics and aliases can be doctested (they work by making
        # a call into a global _ip object).  Also make the top-level get_ipython
        # now return this without recursively calling here again.
        get_ipython = shell.get_ipython
        try:
            import __builtin__
        except:
            import builtins as __builtin__
        __builtin__._ip = shell
        __builtin__.get_ipython = get_ipython

        # We want to print to stdout/err as usual.
        io.stdout = original_stdout
        io.stderr = original_stderr

        self._curr_exec_lines = []
        self.ipython = shell
Пример #24
0
def ipython():
    config = default_config()
    config.TerminalInteractiveShell.simple_prompt = True
    shell = TerminalInteractiveShell.instance(config=config)
    return shell
Пример #25
0
def start_ipython():
    """Start a global IPython shell, which we need for IPython-specific syntax.
    """
    global get_ipython

    # This function should only ever run once!
    if hasattr(start_ipython, 'already_called'):
        return
    start_ipython.already_called = True

    # Store certain global objects that IPython modifies
    _displayhook = sys.displayhook
    _excepthook = sys.excepthook
    _main = sys.modules.get('__main__')

    # Create custom argv and namespaces for our IPython to be test-friendly
    config = tools.default_config()

    # Create and initialize our test-friendly IPython instance.
    shell = TerminalInteractiveShell.instance(config=config,
                                              )

    # A few more tweaks needed for playing nicely with doctests...

    # remove history file
    shell.tempfiles.append(config.HistoryManager.hist_file)

    # These traps are normally only active for interactive use, set them
    # permanently since we'll be mocking interactive sessions.
    shell.builtin_trap.activate()

    # Modify the IPython system call with one that uses getoutput, so that we
    # can capture subcommands and print them to Python's stdout, otherwise the
    # doctest machinery would miss them.
    shell.system = py3compat.MethodType(xsys, shell)
    
    shell._showtraceback = py3compat.MethodType(_showtraceback, shell)

    # IPython is ready, now clean up some global state...

    # Deactivate the various python system hooks added by ipython for
    # interactive convenience so we don't confuse the doctest system
    sys.modules['__main__'] = _main
    sys.displayhook = _displayhook
    sys.excepthook = _excepthook

    # So that ipython magics and aliases can be doctested (they work by making
    # a call into a global _ip object).  Also make the top-level get_ipython
    # now return this without recursively calling here again.
    _ip = shell
    get_ipython = _ip.get_ipython
    builtin_mod._ip = _ip
    builtin_mod.get_ipython = get_ipython

    # To avoid extra IPython messages during testing, suppress io.stdout/stderr
    io.stdout = StreamProxy('stdout')
    io.stderr = StreamProxy('stderr')
    
    # Override paging, so we don't require user interaction during the tests.
    def nopage(strng, start=0, screen_lines=0, pager_cmd=None):
        print(strng)
    
    page.orig_page = page.page
    page.page = nopage

    return _ip
Пример #26
0
    def __init__(self, color_scheme=None, completekey=None,
                 stdin=None, stdout=None, context=5, **kwargs):
        """Create a new IPython debugger.

        Parameters
        ----------
        color_scheme : default None
            Deprecated, do not use.
        completekey : default None
            Passed to pdb.Pdb.
        stdin : default None
            Passed to pdb.Pdb.
        stdout : default None
            Passed to pdb.Pdb.
        context : int
            Number of lines of source code context to show when
            displaying stacktrace information.
        **kwargs
            Passed to pdb.Pdb.

        Notes
        -----
        The possibilities are python version dependent, see the python
        docs for more info.
        """

        # Parent constructor:
        try:
            self.context = int(context)
            if self.context <= 0:
                raise ValueError("Context must be a positive integer")
        except (TypeError, ValueError) as e:
                raise ValueError("Context must be a positive integer") from e

        # `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`.
        OldPdb.__init__(self, completekey, stdin, stdout, **kwargs)

        # IPython changes...
        self.shell = get_ipython()

        if self.shell is None:
            save_main = sys.modules['__main__']
            # No IPython instance running, we must create one
            from IPython.terminal.interactiveshell import \
                TerminalInteractiveShell
            self.shell = TerminalInteractiveShell.instance()
            # needed by any code which calls __import__("__main__") after
            # the debugger was entered. See also #9941.
            sys.modules["__main__"] = save_main

        if color_scheme is not None:
            warnings.warn(
                "The `color_scheme` argument is deprecated since version 5.1",
                DeprecationWarning, stacklevel=2)
        else:
            color_scheme = self.shell.colors

        self.aliases = {}

        # Create color table: we copy the default one from the traceback
        # module and add a few attributes needed for debugging
        self.color_scheme_table = exception_colors()

        # shorthands
        C = coloransi.TermColors
        cst = self.color_scheme_table

        cst['NoColor'].colors.prompt = C.NoColor
        cst['NoColor'].colors.breakpoint_enabled = C.NoColor
        cst['NoColor'].colors.breakpoint_disabled = C.NoColor

        cst['Linux'].colors.prompt = C.Green
        cst['Linux'].colors.breakpoint_enabled = C.LightRed
        cst['Linux'].colors.breakpoint_disabled = C.Red

        cst['LightBG'].colors.prompt = C.Blue
        cst['LightBG'].colors.breakpoint_enabled = C.LightRed
        cst['LightBG'].colors.breakpoint_disabled = C.Red

        cst['Neutral'].colors.prompt = C.Blue
        cst['Neutral'].colors.breakpoint_enabled = C.LightRed
        cst['Neutral'].colors.breakpoint_disabled = C.Red

        # Add a python parser so we can syntax highlight source while
        # debugging.
        self.parser = PyColorize.Parser(style=color_scheme)
        self.set_colors(color_scheme)

        # Set the prompt - the default prompt is '(Pdb)'
        self.prompt = prompt
        self.skip_hidden = True
        self.report_skipped = True

        # list of predicates we use to skip frames
        self._predicates = self.default_predicates
Пример #27
0
    def __init__(self, color_scheme="NoColor", completekey=None, stdin=None, stdout=None):

        # Parent constructor:
        if has_pydb and completekey is None:
            OldPdb.__init__(self, stdin=stdin, stdout=io.stdout)
        else:
            OldPdb.__init__(self, completekey, stdin, stdout)

        # IPython changes...
        self.is_pydb = has_pydb

        self.shell = get_ipython()

        if self.shell is None:
            # No IPython instance running, we must create one
            from IPython.terminal.interactiveshell import TerminalInteractiveShell

            self.shell = TerminalInteractiveShell.instance()

        if self.is_pydb:

            # interactiveshell.py's ipalias seems to want pdb's checkline
            # which located in pydb.fn
            import pydb.fns

            self.checkline = lambda filename, lineno: pydb.fns.checkline(self, filename, lineno)

            self.curframe = None
            self.do_restart = self.new_do_restart

            self.old_all_completions = self.shell.Completer.all_completions
            self.shell.Completer.all_completions = self.all_completions

            self.do_list = decorate_fn_with_doc(self.list_command_pydb, OldPdb.do_list)
            self.do_l = self.do_list
            self.do_frame = decorate_fn_with_doc(self.new_do_frame, OldPdb.do_frame)

        self.aliases = {}

        # Create color table: we copy the default one from the traceback
        # module and add a few attributes needed for debugging
        self.color_scheme_table = exception_colors()

        # shorthands
        C = coloransi.TermColors
        cst = self.color_scheme_table

        cst["NoColor"].colors.prompt = C.NoColor
        cst["NoColor"].colors.breakpoint_enabled = C.NoColor
        cst["NoColor"].colors.breakpoint_disabled = C.NoColor

        cst["Linux"].colors.prompt = C.Green
        cst["Linux"].colors.breakpoint_enabled = C.LightRed
        cst["Linux"].colors.breakpoint_disabled = C.Red

        cst["LightBG"].colors.prompt = C.Blue
        cst["LightBG"].colors.breakpoint_enabled = C.LightRed
        cst["LightBG"].colors.breakpoint_disabled = C.Red

        self.set_colors(color_scheme)

        # Add a python parser so we can syntax highlight source while
        # debugging.
        self.parser = PyColorize.Parser()

        # Set the prompt
        Colors = cst.active_colors
        self.prompt = u"%s%s%s" % (Colors.prompt, prompt, Colors.Normal)  # The default prompt is '(Pdb)'
Пример #28
0
    def __init__(self,color_scheme='NoColor',completekey=None,
                 stdin=None, stdout=None, context=5):

        # Parent constructor:
        try:
            self.context=int(context)
            if self.context <= 0:
                raise ValueError("Context must be a positive integer")
        except (TypeError, ValueError):
                raise ValueError("Context must be a positive integer")

        if has_pydb and completekey is None:
            OldPdb.__init__(self,stdin=stdin,stdout=io.stdout)
        else:
            OldPdb.__init__(self,completekey,stdin,stdout)

        # IPython changes...
        self.is_pydb = has_pydb

        self.shell = get_ipython()

        if self.shell is None:
            # No IPython instance running, we must create one
            from IPython.terminal.interactiveshell import \
                TerminalInteractiveShell
            self.shell = TerminalInteractiveShell.instance()

        if self.is_pydb:

            # interactiveshell.py's ipalias seems to want pdb's checkline
            # which located in pydb.fn
            import pydb.fns
            self.checkline = lambda filename, lineno: \
                             pydb.fns.checkline(self, filename, lineno)

            self.curframe = None
            self.do_restart = self.new_do_restart

            self.old_all_completions = self.shell.Completer.all_completions
            self.shell.Completer.all_completions=self.all_completions

            self.do_list = decorate_fn_with_doc(self.list_command_pydb,
                                                OldPdb.do_list)
            self.do_l     = self.do_list
            self.do_frame = decorate_fn_with_doc(self.new_do_frame,
                                                 OldPdb.do_frame)

        self.aliases = {}

        # Create color table: we copy the default one from the traceback
        # module and add a few attributes needed for debugging
        self.color_scheme_table = exception_colors()

        # shorthands
        C = coloransi.TermColors
        cst = self.color_scheme_table

        cst['NoColor'].colors.prompt = C.NoColor
        cst['NoColor'].colors.breakpoint_enabled = C.NoColor
        cst['NoColor'].colors.breakpoint_disabled = C.NoColor

        cst['Linux'].colors.prompt = C.Green
        cst['Linux'].colors.breakpoint_enabled = C.LightRed
        cst['Linux'].colors.breakpoint_disabled = C.Red

        cst['LightBG'].colors.prompt = C.Blue
        cst['LightBG'].colors.breakpoint_enabled = C.LightRed
        cst['LightBG'].colors.breakpoint_disabled = C.Red

        self.set_colors(color_scheme)

        # Add a python parser so we can syntax highlight source while
        # debugging.
        self.parser = PyColorize.Parser()

        # Set the prompt - the default prompt is '(Pdb)'
        Colors = cst.active_colors
        if color_scheme == 'NoColor':
            self.prompt = prompt
        else:
            # The colour markers are wrapped by bytes 01 and 02 so that readline
            # can calculate the width.
            self.prompt = u'\x01%s\x02%s\x01%s\x02' % (Colors.prompt, prompt, Colors.Normal)
Пример #29
0
def ipython():
    config = default_config()
    config.TerminalInteractiveShell.simple_prompt = True
    shell = TerminalInteractiveShell.instance(config=config)
    return shell
Пример #30
0
    def __init__(self,
                 color_scheme='NoColor',
                 completekey=None,
                 stdin=None,
                 stdout=None):

        # Parent constructor:
        if has_pydb and completekey is None:
            OldPdb.__init__(self, stdin=stdin, stdout=io.stdout)
        else:
            OldPdb.__init__(self, completekey, stdin, stdout)

        self.prompt = prompt  # The default prompt is '(Pdb)'

        # IPython changes...
        self.is_pydb = has_pydb

        self.shell = get_ipython()

        if self.shell is None:
            # No IPython instance running, we must create one
            from IPython.terminal.interactiveshell import \
                TerminalInteractiveShell
            self.shell = TerminalInteractiveShell.instance()

        if self.is_pydb:

            # interactiveshell.py's ipalias seems to want pdb's checkline
            # which located in pydb.fn
            import pydb.fns
            self.checkline = lambda filename, lineno: \
                             pydb.fns.checkline(self, filename, lineno)

            self.curframe = None
            self.do_restart = self.new_do_restart

            self.old_all_completions = self.shell.Completer.all_completions
            self.shell.Completer.all_completions = self.all_completions

            self.do_list = decorate_fn_with_doc(self.list_command_pydb,
                                                OldPdb.do_list)
            self.do_l = self.do_list
            self.do_frame = decorate_fn_with_doc(self.new_do_frame,
                                                 OldPdb.do_frame)

        self.aliases = {}

        # Create color table: we copy the default one from the traceback
        # module and add a few attributes needed for debugging
        self.color_scheme_table = exception_colors()

        # shorthands
        C = coloransi.TermColors
        cst = self.color_scheme_table

        cst['NoColor'].colors.breakpoint_enabled = C.NoColor
        cst['NoColor'].colors.breakpoint_disabled = C.NoColor

        cst['Linux'].colors.breakpoint_enabled = C.LightRed
        cst['Linux'].colors.breakpoint_disabled = C.Red

        cst['LightBG'].colors.breakpoint_enabled = C.LightRed
        cst['LightBG'].colors.breakpoint_disabled = C.Red

        self.set_colors(color_scheme)

        # Add a python parser so we can syntax highlight source while
        # debugging.
        self.parser = PyColorize.Parser()
Пример #31
0
def ipython(ipython_dir):
    config = default_config()
    config.TerminalInteractiveShell.simple_prompt = True
    shell = TerminalInteractiveShell.instance(config=config)
    yield shell
    TerminalInteractiveShell.clear_instance()
    def __init__(self,
                 color_scheme='NoColor',
                 completekey=None,
                 stdin=None,
                 stdout=None,
                 context=5):

        # Parent constructor:
        try:
            self.context = int(context)
            if self.context <= 0:
                raise ValueError("Context must be a positive integer")
        except (TypeError, ValueError):
            raise ValueError("Context must be a positive integer")

        if has_pydb and completekey is None:
            OldPdb.__init__(self, stdin=stdin, stdout=io.stdout)
        else:
            OldPdb.__init__(self, completekey, stdin, stdout)

        # IPython changes...
        self.is_pydb = has_pydb

        self.shell = get_ipython()

        if self.shell is None:
            # No IPython instance running, we must create one
            from IPython.terminal.interactiveshell import \
                TerminalInteractiveShell
            self.shell = TerminalInteractiveShell.instance()

        if self.is_pydb:

            # interactiveshell.py's ipalias seems to want pdb's checkline
            # which located in pydb.fn
            import pydb.fns
            self.checkline = lambda filename, lineno: \
                             pydb.fns.checkline(self, filename, lineno)

            self.curframe = None
            self.do_restart = self.new_do_restart

            self.old_all_completions = self.shell.Completer.all_completions
            self.shell.Completer.all_completions = self.all_completions

            self.do_list = decorate_fn_with_doc(self.list_command_pydb,
                                                OldPdb.do_list)
            self.do_l = self.do_list
            self.do_frame = decorate_fn_with_doc(self.new_do_frame,
                                                 OldPdb.do_frame)

        self.aliases = {}

        # Create color table: we copy the default one from the traceback
        # module and add a few attributes needed for debugging
        self.color_scheme_table = exception_colors()

        # shorthands
        C = coloransi.TermColors
        cst = self.color_scheme_table

        cst['NoColor'].colors.prompt = C.NoColor
        cst['NoColor'].colors.breakpoint_enabled = C.NoColor
        cst['NoColor'].colors.breakpoint_disabled = C.NoColor

        cst['Linux'].colors.prompt = C.Green
        cst['Linux'].colors.breakpoint_enabled = C.LightRed
        cst['Linux'].colors.breakpoint_disabled = C.Red

        cst['LightBG'].colors.prompt = C.Blue
        cst['LightBG'].colors.breakpoint_enabled = C.LightRed
        cst['LightBG'].colors.breakpoint_disabled = C.Red

        self.set_colors(color_scheme)

        # Add a python parser so we can syntax highlight source while
        # debugging.
        self.parser = PyColorize.Parser()

        # Set the prompt - the default prompt is '(Pdb)'
        Colors = cst.active_colors
        if color_scheme == 'NoColor':
            self.prompt = prompt
        else:
            # The colour markers are wrapped by bytes 01 and 02 so that readline
            # can calculate the width.
            self.prompt = u'\x01%s\x02%s\x01%s\x02' % (Colors.prompt, prompt,
                                                       Colors.Normal)
Пример #33
0
def start_ipython():
    """Start a global IPython shell, which we need for IPython-specific syntax.
    """
    global get_ipython

    # This function should only ever run once!
    if hasattr(start_ipython, 'already_called'):
        return
    start_ipython.already_called = True

    # Store certain global objects that IPython modifies
    _displayhook = sys.displayhook
    _excepthook = sys.excepthook
    _main = sys.modules.get('__main__')

    # Create custom argv and namespaces for our IPython to be test-friendly
    config = tools.default_config()
    config.TerminalInteractiveShell.simple_prompt = True

    # Create and initialize our test-friendly IPython instance.
    shell = TerminalInteractiveShell.instance(config=config, )

    # A few more tweaks needed for playing nicely with doctests...

    # remove history file
    shell.tempfiles.append(config.HistoryManager.hist_file)

    # These traps are normally only active for interactive use, set them
    # permanently since we'll be mocking interactive sessions.
    shell.builtin_trap.activate()

    # Modify the IPython system call with one that uses getoutput, so that we
    # can capture subcommands and print them to Python's stdout, otherwise the
    # doctest machinery would miss them.
    shell.system = py3compat.MethodType(xsys, shell)

    shell._showtraceback = py3compat.MethodType(_showtraceback, shell)

    # IPython is ready, now clean up some global state...

    # Deactivate the various python system hooks added by ipython for
    # interactive convenience so we don't confuse the doctest system
    sys.modules['__main__'] = _main
    sys.displayhook = _displayhook
    sys.excepthook = _excepthook

    # So that ipython magics and aliases can be doctested (they work by making
    # a call into a global _ip object).  Also make the top-level get_ipython
    # now return this without recursively calling here again.
    _ip = shell
    get_ipython = _ip.get_ipython
    builtin_mod._ip = _ip
    builtin_mod.get_ipython = get_ipython

    # Override paging, so we don't require user interaction during the tests.
    def nopage(strng, start=0, screen_lines=0, pager_cmd=None):
        if isinstance(strng, dict):
            strng = strng.get('text/plain', '')
        print(strng)

    page.orig_page = page.pager_page
    page.pager_page = nopage

    return _ip
Пример #34
0
    def __init__(self,
                 color_scheme=None,
                 completekey=None,
                 stdin=None,
                 stdout=None,
                 context=5):

        # Parent constructor:
        try:
            self.context = int(context)
            if self.context <= 0:
                raise ValueError("Context must be a positive integer")
        except (TypeError, ValueError):
            raise ValueError("Context must be a positive integer")

        OldPdb.__init__(self, completekey, stdin, stdout)

        # IPython changes...
        self.shell = get_ipython()

        if self.shell is None:
            save_main = sys.modules['__main__']
            # No IPython instance running, we must create one
            from IPython.terminal.interactiveshell import \
                TerminalInteractiveShell
            self.shell = TerminalInteractiveShell.instance()
            # needed by any code which calls __import__("__main__") after
            # the debugger was entered. See also #9941.
            sys.modules['__main__'] = save_main

        if color_scheme is not None:
            warnings.warn(
                "The `color_scheme` argument is deprecated since version 5.1",
                DeprecationWarning)
        else:
            color_scheme = self.shell.colors

        self.aliases = {}

        # Create color table: we copy the default one from the traceback
        # module and add a few attributes needed for debugging
        self.color_scheme_table = exception_colors()

        # shorthands
        C = coloransi.TermColors
        cst = self.color_scheme_table

        cst['NoColor'].colors.prompt = C.NoColor
        cst['NoColor'].colors.breakpoint_enabled = C.NoColor
        cst['NoColor'].colors.breakpoint_disabled = C.NoColor

        cst['Linux'].colors.prompt = C.Green
        cst['Linux'].colors.breakpoint_enabled = C.LightRed
        cst['Linux'].colors.breakpoint_disabled = C.Red

        cst['LightBG'].colors.prompt = C.Blue
        cst['LightBG'].colors.breakpoint_enabled = C.LightRed
        cst['LightBG'].colors.breakpoint_disabled = C.Red

        cst['Neutral'].colors.prompt = C.Blue
        cst['Neutral'].colors.breakpoint_enabled = C.LightRed
        cst['Neutral'].colors.breakpoint_disabled = C.Red

        self.set_colors(color_scheme)

        # Add a python parser so we can syntax highlight source while
        # debugging.
        self.parser = PyColorize.Parser()

        # Set the prompt - the default prompt is '(Pdb)'
        self.prompt = prompt