Beispiel #1
0
def openRepl(self):
    orig_stdin = sys.stdin
    orig_stdout = sys.stdout
    try:
        # Provide local top-level access to VisiData global and sheet-local
        # variables, similar to VisiData's `execCommand` context.
        new_locals = LazyChainMap(Dummy(), vd, vd.sheet)
        locals().update(new_locals)
    except Exception as e:
        vd.exceptionCaught(e)

    with SuspendCurses():
        try:
            sys.stdin = vd._stdin
            sys.stdout = open('/dev/tty', mode='w')
            history_file = (Path(vd.options.visidata_dir).expanduser() /
                            'cache' / 'ptpython' / 'history')
            Path.mkdir(history_file.parent, parents=True, exist_ok=True)
            shell = InteractiveShellEmbed.instance(
                history_filename=str(history_file),
                vi_mode=True,
            )
            shell.python_input.title = 'VisiData IPython REPL (ptipython)'
            shell.python_input.show_exit_confirmation = False
            embed()
        except Exception as e:
            vd.exceptionCaught(e)
        finally:
            sys.stdin = orig_stdin
            sys.stdout = orig_stdout
Beispiel #2
0
def openRepl(self):
    """Open a ptipython-based REPL that inherits VisiData's context."""
    try:
        # Provide local top-level access to VisiData global and sheet-local
        # variables, similar to VisiData's `execCommand` context.
        new_locals = LazyChainMap(Dummy(), vd, vd.sheet)
        locals().update(new_locals)
    except Exception as e:
        vd.exceptionCaught(e)

    with SuspendCurses():
        try:
            history_file = (Path(vd.options.visidata_dir).expanduser() /
                            "cache" / "ptpython" / "history")
            Path.mkdir(history_file.parent, parents=True, exist_ok=True)
            shell = InteractiveShellEmbed.instance(
                history_filename=str(history_file),
                vi_mode=True,
            )
            shell.python_input.title = "VisiData IPython REPL (ptipython)"
            shell.python_input.show_exit_confirmation = False
            embed()
        except Exception as e:
            vd.exceptionCaught(e)
        finally:
            # The embedded IPython session is a singleton by default,
            # but launching it via `open-repl` in VisiData a second time
            # seems to either freeze or leave an exit message up from the
            # previous instance. Clean out the existing instance so any
            # future invocations get a fresh start.
            InteractiveShellEmbed.clear_instance()
Beispiel #3
0
def run():
    a = docopt.docopt(__doc__)

    vi_mode = bool(a['--vi'])
    config_dir = os.path.expanduser(a['--config-dir'] or '~/.ptpython/')

    # If IPython is not available, show message and exit here with error status
    # code.
    try:
        import IPython
    except ImportError:
        print('IPython not found. Please install IPython (pip install ipython).')
        sys.exit(1)
    else:
        from ptpython.ipython import embed
        from ptpython.repl import run_config, enable_deprecation_warnings

    # Add the current directory to `sys.path`.
    if sys.path[0] != '':
        sys.path.insert(0, '')

    # When a file has been given, run that, otherwise start the shell.
    if a['<file>']:
        sys.argv = [a['<file>']] + a['<arg>']
        six.exec_(compile(open(a['<file>'], "rb").read(), a['<file>'], 'exec'))
    else:
        enable_deprecation_warnings()

        # Create an empty namespace for this interactive shell. (If we don't do
        # that, all the variables from this function will become available in
        # the IPython shell.)
        user_ns = {}

        # --interactive
        if a['--interactive']:
            path = a['--interactive']

            if os.path.exists(path):
                with open(path, 'r') as f:
                    code = compile(f.read(), path, 'exec')
                    six.exec_(code, user_ns, user_ns)
            else:
                print('File not found: {}\n\n'.format(path))
                sys.exit(1)

        # Apply config file
        def configure(repl):
            path = os.path.join(config_dir, 'config.py')
            if os.path.exists(path):
                run_config(repl, path)

        # Run interactive shell.
        embed(vi_mode=vi_mode,
              history_filename=os.path.join(config_dir, 'history'),
              configure=configure,
              user_ns=user_ns,
              title='IPython REPL (ptipython)')
def ipython(log_dir: Optional[str], vi_mode: bool) -> None:
    if log_dir is not None:
        log = ExperimentLog(log_dir)  # noqa
    else:
        open_log = ExperimentLog  # noqa
    try:
        from ptpython.ipython import embed
        from matplotlib import pyplot as plt  # noqa
        import rainy  # noqa
        del log_dir
        embed(vi_mode=vi_mode)
    except ImportError:
        print("To use ipython mode, install ipython and ptpython first.")
Beispiel #5
0
def ipython(ctx: dict, log_dir: Optional[str], vi_mode: bool) -> None:
    config, make_agent = ctx.obj['config'], ctx.obj['make_agent']  # noqa
    if log_dir is not None:
        log = ExperimentLog(log_dir)  # noqa
    else:
        open_log = ExperimentLog  # noqa
    try:
        from ptpython.ipython import embed
        del ctx, log_dir
        import rainy  # noqa
        embed(vi_mode=vi_mode)
    except ImportError:
        print("To use ipython mode, install ipython and ptpython first.")
Beispiel #6
0
    def run(self, no_ipython, no_bpython, no_ptipython, no_ptpython):
        """
        Runs the shell.
        If no_ptipython is False or use_ptipython is True, then a PtIPython shell is run (if installed).
        If no_ptpython is False or use_ptpython is True, then a PtPython shell is run (if installed).
        If no_bpython is False or use_bpython is True, then a BPython shell is run (if installed).
        If no_ipython is False or use_python is True then a IPython shell is run (if installed).
        """

        context = self.get_context()

        if not no_ptipython:
            # Try PtIPython
            try:
                from ptpython.ipython import embed

                history_filename = os.path.expanduser("~/.ptpython_history")
                embed(
                    banner1=self.banner,
                    user_ns=context,
                    history_filename=history_filename,
                )
                return
            except ImportError:
                pass

        if not no_ptpython:
            # Try PtPython
            try:
                from ptpython.repl import embed

                history_filename = os.path.expanduser("~/.ptpython_history")
                embed(globals=context, history_filename=history_filename)
                return
            except ImportError:
                pass

        if not no_bpython:
            # Try BPython
            try:
                from bpython import embed

                embed(banner=self.banner, locals_=context)
                return
            except ImportError:
                pass

        if not no_ipython:
            # Try IPython
            try:
                from IPython import embed

                embed(banner1=self.banner, user_ns=context)
                return
            except ImportError:
                pass

        # Use basic python shell
        code.interact(self.banner, local=context)
    def run(self, no_ipython, no_bpython, no_ptipython, no_ptpython):
        """
        Runs the shell.
        If no_ptipython is False or use_ptipython is True, then a PtIPython shell is run (if installed).
        If no_ptpython is False or use_ptpython is True, then a PtPython shell is run (if installed).
        If no_bpython is False or use_bpython is True, then a BPython shell is run (if installed).
        If no_ipython is False or use_python is True then a IPython shell is run (if installed).
        """

        context = self.get_context()

        if not no_ptipython:
            # Try PtIPython
            try:
                from ptpython.ipython import embed
                history_filename = os.path.expanduser('~/.ptpython_history')
                embed(banner1=self.banner, user_ns=context, history_filename=history_filename)
                return
            except ImportError:
                pass

        if not no_ptpython:
            # Try PtPython
            try:
                from ptpython.repl import embed
                history_filename = os.path.expanduser('~/.ptpython_history')
                embed(globals=context, history_filename=history_filename)
                return
            except ImportError:
                pass

        if not no_bpython:
            # Try BPython
            try:
                from bpython import embed
                embed(banner=self.banner, locals_=context)
                return
            except ImportError:
                pass

        if not no_ipython:
            # Try IPython
            try:
                from IPython import embed
                embed(banner1=self.banner, user_ns=context)
                return
            except ImportError:
                pass

        # Use basic python shell
        code.interact(self.banner, local=context)
Beispiel #8
0
def run():
    a = docopt.docopt(__doc__)

    vi_mode = bool(a['--vi'])

    # If IPython is not available, show message and exit here with error status
    # code.
    try:
        import IPython
    except ImportError:
        print('IPython not found. Please install IPython (pip install ipython).')
        sys.exit(1)
    else:
        from ptpython.ipython import embed

    # Log history
    if a['--history']:
        history_filename = os.path.expanduser(a['--history'])
    else:
        history_filename = os.path.expanduser('~/.ptpython_history')

    # Add the current directory to `sys.path`.
    sys.path.append('.')

    # When a file has been given, run that, otherwise start the shell.
    if a['<file>']:
        sys.argv = [a['<file>']] + a['<arg>']
        six.exec_(compile(open(a['<file>'], "rb").read(), a['<file>'], 'exec'))
    else:
        # Create an empty namespace for this interactive shell. (If we don't do
        # that, all the variables from this function will become available in
        # the IPython shell.)
        user_ns = {}

        # Run interactive shell.
        embed(vi_mode=vi_mode, history_filename=history_filename, user_ns=user_ns)
Beispiel #9
0
def pudb_shell(_globals, _locals) -> None:
    """
    This example shell runs a classic Python shell. It is based on
    run_classic_shell in pudb.shell.

    """
    # Many shells only let you pass in a single locals dictionary, rather than
    # separate globals and locals dictionaries. In this case, you can use
    # pudb.shell.SetPropagatingDict to automatically merge the two into a
    # single dictionary. It does this in such a way that assignments propogate
    # to _locals, so that when the debugger is at the module level, variables
    # can be reassigned in the shell.
    import os.path
    from ptpython.ipython import embed
    from ptpython.repl import run_config

    history_filename = os.path.expanduser('~/.config/ptpython/history')

    embed(
        globals=_globals,
        locals=_locals,
        history_filename=history_filename,
        configure=run_config,
    )
Beispiel #10
0
    def run(self, app, args):
        """
        Logic copied from https://github.com/smurfix/flask-script/blob/master/flask_script/commands.py
        """
        context = self.create_context(app)

        if not args.no_ptipython:
            # Try PtIPython
            try:
                from ptpython.ipython import embed
                history_filename = os.path.expanduser('~/.ptpython_history')
                embed(banner1=self.banner, user_ns=context, history_filename=history_filename)
                return
            except ImportError:
                pass

        if not args.no_ptpython:
            # Try PtPython
            try:
                from ptpython.repl import embed
                history_filename = os.path.expanduser('~/.ptpython_history')
                embed(globals=context, history_filename=history_filename)
                return
            except ImportError:
                pass

        if not args.no_bpython:
            # Try BPython
            try:
                from bpython import embed
                embed(banner=self.banner, locals_=context)
                return
            except ImportError:
                pass

        if not args.no_ipython:
            # Try IPython
            try:
                from IPython import embed
                embed(banner1=self.banner, user_ns=context)
                return
            except ImportError:
                pass

        code.interact(self.banner, local=context)
Beispiel #11
0
    def run(self, app, args):
        """
        Logic copied from https://github.com/smurfix/flask-script/blob/master/flask_script/commands.py
        """
        context = self.create_context(app)

        if not args.no_ptipython:
            # Try PtIPython
            try:
                from ptpython.ipython import embed
                history_filename = os.path.expanduser('~/.ptpython_history')
                embed(banner1=self.banner, user_ns=context, history_filename=history_filename)
                return
            except ImportError:
                pass

        if not args.no_ptpython:
            # Try PtPython
            try:
                from ptpython.repl import embed
                history_filename = os.path.expanduser('~/.ptpython_history')
                embed(globals=context, history_filename=history_filename)
                return
            except ImportError:
                pass

        if not args.no_bpython:
            # Try BPython
            try:
                from bpython import embed
                embed(banner=self.banner, locals_=context)
                return
            except ImportError:
                pass

        if not args.no_ipython:
            # Try IPython
            try:
                from IPython import embed
                embed(banner1=self.banner, user_ns=context)
                return
            except ImportError:
                pass

        code.interact(self.banner, local=context)
Beispiel #12
0
def shell():
    """Runs a Python shell inside application context"""
    from badwolf.wsgi import app

    app.debug = True
    context = {
        'app': app,
    }

    with app.app_context():
        # Try ptpython
        try:
            from ptpython.ipython import embed
            embed(user_ns=context, vi_mode=True)
            return
        except ImportError:
            pass

        # Try bpython
        try:
            from bpython import embed
            embed(locals_=context)
            return
        except ImportError:
            pass

        # Try ipython
        try:
            try:
                # 0.10.x
                from IPython.Shell import IPShellEmbed
                ipshell = IPShellEmbed(banner='Welcome to badwolf shell\n')
                ipshell(global_ns=dict(), local_ns=context)
            except ImportError:
                # 0.12+
                from IPython import embed
                embed(banner1='Welcome to badwolf shell\n', user_ns=context)
            return
        except ImportError:
            pass

        # Use basic python shell
        import code

        code.interact(local=context)
Beispiel #13
0
def run(user_ns=None):
    a = create_parser().parse_args()

    config_file, history_file = get_config_and_history_file(a)

    # If IPython is not available, show message and exit here with error status
    # code.
    try:
        import IPython
    except ImportError:
        print("IPython not found. Please install IPython (pip install ipython).")
        sys.exit(1)
    else:
        from ptpython.ipython import embed
        from ptpython.repl import enable_deprecation_warnings, run_config

    # Add the current directory to `sys.path`.
    if sys.path[0] != "":
        sys.path.insert(0, "")

    # When a file has been given, run that, otherwise start the shell.
    if a.args and not a.interactive:
        sys.argv = a.args
        path = a.args[0]
        with open(path, "rb") as f:
            code = compile(f.read(), path, "exec")
            exec(code, {})
    else:
        enable_deprecation_warnings()

        # Create an empty namespace for this interactive shell. (If we don't do
        # that, all the variables from this function will become available in
        # the IPython shell.)
        if user_ns is None:
            user_ns = {}

        # Startup path
        startup_paths = []
        if "PYTHONSTARTUP" in os.environ:
            startup_paths.append(os.environ["PYTHONSTARTUP"])

        # --interactive
        if a.interactive:
            startup_paths.append(a.args[0])
            sys.argv = a.args

        # exec scripts from startup paths
        for path in startup_paths:
            if os.path.exists(path):
                with open(path, "rb") as f:
                    code = compile(f.read(), path, "exec")
                    exec(code, user_ns, user_ns)
            else:
                print("File not found: {}\n\n".format(path))
                sys.exit(1)

        # Apply config file
        def configure(repl):
            if os.path.exists(config_file):
                run_config(repl, config_file)

        # Run interactive shell.
        embed(
            vi_mode=a.vi,
            history_filename=history_file,
            configure=configure,
            user_ns=user_ns,
            title="IPython REPL (ptipython)",
        )
def run():
    a = docopt.docopt(__doc__)

    vi_mode = bool(a['--vi'])
    config_dir = os.path.expanduser(a['--config-dir'] or '~/.ptpython/')

    # Create config directory.
    if not os.path.isdir(config_dir):
        os.mkdir(config_dir)

    # If IPython is not available, show message and exit here with error status
    # code.
    try:
        import IPython
    except ImportError:
        print(
            'IPython not found. Please install IPython (pip install ipython).')
        sys.exit(1)
    else:
        from ptpython.ipython import embed
        from ptpython.repl import run_config, enable_deprecation_warnings

    # Add the current directory to `sys.path`.
    if sys.path[0] != '':
        sys.path.insert(0, '')

    # When a file has been given, run that, otherwise start the shell.
    if a['<arg>'] and not a['--interactive']:
        sys.argv = a['<arg>']
        six.exec_(
            compile(open(a['<arg>'][0], "rb").read(), a['<arg>'][0], 'exec'))
    else:
        enable_deprecation_warnings()

        # Create an empty namespace for this interactive shell. (If we don't do
        # that, all the variables from this function will become available in
        # the IPython shell.)
        user_ns = {}

        # Startup path
        startup_paths = []
        if 'PYTHONSTARTUP' in os.environ:
            startup_paths.append(os.environ['PYTHONSTARTUP'])

        # --interactive
        if a['--interactive']:
            startup_paths.append(a['--interactive'])
            sys.argv = [a['--interactive']] + a['<arg>']

        # exec scripts from startup paths
        for path in startup_paths:
            if os.path.exists(path):
                with open(path, 'r') as f:
                    code = compile(f.read(), path, 'exec')
                    six.exec_(code, user_ns, user_ns)
            else:
                print('File not found: {}\n\n'.format(path))
                sys.exit(1)

        # Apply config file
        def configure(repl):
            path = os.path.join(config_dir, 'config.py')
            if os.path.exists(path):
                run_config(repl, path)

        # Run interactive shell.
        embed(vi_mode=vi_mode,
              history_filename=os.path.join(config_dir, 'history'),
              configure=configure,
              user_ns=user_ns,
              title='IPython REPL (ptipython)')
Beispiel #15
0
def ptpython_shell(ctx, banner):
    from ptpython.repl import embed
    embed(globals=ctx)
Beispiel #16
0
def ipython_shell(ctx, banner):
    from IPython import embed
    embed(banner1=banner, user_ns=ctx)
Beispiel #17
0
def bpython_shell(ctx, banner):
    from bpython import embed
    embed(banner=banner, locals_=ctx)
Beispiel #18
0
def ptipython_shell(ctx, banner):
    from ptpython.ipython import embed
    embed(banner1=banner, user_ns=ctx)