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)

    # 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>']

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

    if "VIRTUAL_ENV" in os.environ:
        virtual_env = Path(
            os.environ.get("VIRTUAL_ENV"),
            "lib",
            "python{0}.{1}".format(*sys.version_info[0:2]),
            "site-packages",
        )
        if virtual_env.exists():
            site.addsitedir(str(virtual_env))

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

    # Run interactive shell.
    else:
        enable_deprecation_warnings()

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

        import __main__
        embed(vi_mode=vi_mode,
              history_filename=os.path.join(config_dir, 'history'),
              configure=configure,
              locals=__main__.__dict__,
              globals=__main__.__dict__,
              startup_paths=startup_paths,
              title='Python REPL (ptpython)')
Example #2
0
def cli():
    """
    Commandline for looter!
    """
    argv = docopt(__doc__, version=VERSION)
    if argv['genspider']:
        template = argv['<tmpl>']
        name = argv['<name>']
        async_ = argv['--async']
        if template not in ['data', 'image']:
            exit('Plz provide a template (data, image)')
        if async_:
            template = f'{template}_async'
        package_dir = Path(__file__).parent
        template_text = package_dir.joinpath('templates', f'{template}.tmpl').read_text()
        Path(f'{name}.py').write_text(template_text)
    if argv['shell']:
        if not argv['<url>']:
            url = input('Which site do u want to crawl?\nurl: ')
        else:
            url = argv['<url>']
        res = send_request(url)
        if not res:
            exit('Failed to fetch the page.')
        tree = Selector(text=res.text)
        allvars = {**locals(), **globals()}
        try:
            from ptpython.repl import embed
            print(BANNER)
            embed(allvars)
        except ImportError:
            code.interact(local=allvars, banner=BANNER)
Example #3
0
    def start(self) -> None:
        try:
            from ptpython.repl import embed, run_config
        except ImportError:
            raise ShellNotAvailableError("PtPython shell not available.")
        print(self.banner)

        config_dir = Path("~/.ptpython/").expanduser()

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

        # Apply config file
        def configure(repl):
            path = config_dir / "config.py"
            if path.exists():
                run_config(repl, str(path))

        embed(
            globals=self.context,
            history_filename=config_dir / "history",
            vi_mode=self.ptpy_vi_mode,
            startup_paths=startup_paths,
            configure=configure,
        )
        return None
Example #4
0
def python(env, args, kwargs):
    """[STRING,...]@Drop into a python REPL. If STRINGs specified, execute them in Python."""
    temp_space = globals()
    if args != []:
        if "string" in kwargs and kwargs["string"]:
            # strings are to be run
            for arg in args:
                exec(arg, temp_space)
                return ""
        else:
            # files are to be run
            for arg in args:
                execfile(arg, temp_space)
                return ""
    else:
        try:
            temp_space = globals()
            temp_space.update({"exit": sys.exit})
            temp_space.update({"quit": sys.exit})
            temp_space.update(env.namespace)
            temp_space.update({"shutil": shutil})
            temp_space.update({"os": os})
            temp_space.update({"ergo": env.ergo})

            _vi_mode = False
            if env.EDITOR in ["vi", "vim"]:
                _vi_mode = True

            embed(globals(), temp_space, vi_mode=_vi_mode)
        except SystemExit:
            pass

    for key in temp_space:
        env.namespace[key] = temp_space[key]
    return ""
Example #5
0
 def process_input(self, character):
     self.window.window.clear()
     if character == 263 and self.buffer:     # Handle backspace
         self.buffer = self.buffer[:-1]
     elif character == 10 or character == 13: # Handle the return key
         inputs = self.buffer.split("\n")
         if "menu" in inputs:
             menu = self.window.get("menu")
             menu.hidden = False if menu.hidden else True
             menu.active = True if not menu.active else False
         # Yup... Can launch ptpython with the "python" command.
         elif "python" in inputs:
             try:
                 from ptpython.repl import embed
                 self.window.stop()
                 l = {"pane": self, "window": self.window}
                 embed(locals=l, vi_mode=True)
                 self.buffer = ""
                 self.window.start()
             except:
                 pass
         elif "exit" in inputs:
             self.window.stop()
         self.buffer = ""
     else:
         try: self.buffer += chr(character)   # Append input to buffer
         except: pass
     import random
     colours = palette(-1, random.choice(["yellow","red"]))
     self.change_content(1, self.buffer, ALIGN_LEFT, colours)
Example #6
0
def cli():
    """
    Commandline for looter :d
    """
    argv = docopt(__doc__, version=VERSION)
    if argv['genspider']:
        name = f"{argv['<name>']}.py"
        use_async = argv['--async']
        template = 'data_async.tmpl' if use_async else 'data.tmpl'
        package_dir = Path(__file__).parent
        template_text = package_dir.joinpath('templates', template).read_text()
        Path(name).write_text(template_text)
    if argv['shell']:
        url = argv['<url>'] if argv['<url>'] else input(
            'Plz specific a site to crawl\nurl: ')
        url = ensure_schema(url)
        res = requests.get(url, headers=DEFAULT_HEADERS)
        if not res:
            exit('Failed to fetch the page.')
        tree = Selector(text=res.text)
        allvars = {**locals(), **globals()}
        try:
            from ptpython.repl import embed
            print(BANNER)
            embed(allvars)
        except ImportError:
            code.interact(local=allvars, banner=BANNER)
Example #7
0
def cli():
    """
    Commandline for looter!
    """
    argv = docopt(__doc__, version=VERSION)
    if argv['genspider']:
        template = argv['<tmpl>']
        name = argv['<name>']
        async_ = argv['--async']
        if template not in ['data', 'image']:
            exit('Plz provide a template (data, image)')
        if async_:
            template = template + '_async'
        package_path = os.path.dirname(__file__)
        with open(f'{package_path}\\templates\\{template}.tmpl',
                  'r') as i, open(f'{name}.py', 'w') as o:
            o.write(i.read())

    if argv['shell']:
        if not argv['<url>']:
            url = input('Which site do u want to crawl?\nurl: ')
        else:
            url = argv['<url>']
        res = send_request(url)
        if not res:
            exit('Failed to fetch the page.')
        tree = etree.HTML(res.text)
        allvars = {**locals(), **globals()}
        try:
            from ptpython.repl import embed
            print(BANNER)
            embed(allvars)
        except ImportError:
            code.interact(local=allvars, banner=BANNER)
Example #8
0
def interactive(toplevel, *files, namespace=None, libraries=None, **keywords):
    """
	Launch an interactive interpreter to control the simulator.
	"""
    from ptpython.repl import embed

    with simulate(toplevel, *files, libraries=libraries) as simulator:
        namespace = namespace or {}
        namespace.update({
            'simulator': simulator,
            'run': simulator.run,
            'execute': simulator.execute,
            'examine': simulator.examine,
            'change': simulator.change,
            'force': simulator.force,
            'noforce': simulator.noforce,
            'nets': simulator.nets,
            'signals': simulator.signals,
            'instances': simulator.instances
        })

        embed(namespace, namespace, **keywords)


# Used to record the values of signals and variables in the design
# if we do not log we cannot access data easily
# log -r /*

# grep {type signal_name}
# show path_to_signal
# EXPLORE the serchlog command
# EXPLORE log command to record the value of signals
# log -r /* --- log all signals in the design, needed to look at their past values
Example #9
0
File: konch.py Project: brl0/konch
    def start(self) -> None:
        try:
            from ptpython.repl import embed, run_config
        except ImportError:
            raise ShellNotAvailableError("PtPython shell not available.")
        print(self.banner)

        config_dir = Path("~/.ptpython/").expanduser()

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

        # Apply config file
        def configure(repl):
            path = config_dir / "config.py"
            if path.exists():
                run_config(repl, str(path))

        embed(
            globals=self.context,
            history_filename=config_dir / "history",
            vi_mode=self.ptpy_vi_mode,
            startup_paths=startup_paths,
            configure=configure,
        )
        return None
Example #10
0
def run(args):
    global wd

    if args.path:
        assert wd.create(args.path) == 0
        wd.waitevent()
    elif args.attach:
        try:
            pid = int(args.attach)
            if wd.attach(pid):
                print('Attach failure', pid)
        except ValueError:
            if wd.attach(args.attach):
                print('Attach failure', args.attach)
        wd.waitevent()
    elif args.kernel:
        assert wd.attachkernel(args.kernel) == 0
        wd.waitevent()

    if args.x:
        with open(args.x) as f:
            exec(f.read(), {'wd': wd})

    # waiting for initial breakpoint
    print('---------------------------------------------------------')
    repl.embed(globals(), locals())
Example #11
0
 def do_interact(self, args):
     """
     Interact: start interpreter.
     (Override the 'pdb' implementation. We call ptpython instead.)
     """
     print('')
     embed(globals=self.curframe.f_globals, locals=self.curframe.f_locals)
Example #12
0
def run():
    a = docopt.docopt(__doc__)

    vi_mode = bool(a['--vi'])
    no_colors = bool(a['--no-colors'])

    # Create globals/locals dict.
    globals_, locals_ = {}, {}

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

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

    # --interactive
    if a['--interactive']:
        startup_paths.append(a['--interactive'])

    # 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:
        # Run interactive shell.
        embed(globals_, locals_, vi_mode=vi_mode, history_filename=history_filename,
              no_colors=no_colors, startup_paths=startup_paths)
Example #13
0
def run_shell(wsgi_app: 'Flask'):
    from nkzalimi.web import app
    from ptpython.repl import embed
    l = locals()
    wsgi_app.app_context().push()
    l['session'] = app.create_session()
    embed(globals(), l)
Example #14
0
def main():
    import sys
    try:
        with open("/var/smulliga/source/git/mullikine/codenames/sentence.txt", "r") as infile:
            lines = infile.readlines()[0]
            lines = b("sed 's/[,.;]/ & /g' | sed 's/ \+/ /g'", lines)
            # lines = b("escape-11.05.19.sh", lines)
            line = lines[0].lower()

            lwvec = []
            for w in line.split(" "):
                try:
                    lwvec.append(list(word_to_vector(w)))
                    # print(np.array(lwvec).shape)
                except Exception:
                    print(w)

            # lwvec.append(np.zeros((1,300)))

    except IOError:
        print >> sys.stderr, "Some I/O Error occurred"
        sys.exit(1)


    word_to_vector("hand")
    from ptpython.repl import embed
    embed(globals(), locals())
Example #15
0
    def Insert_rule(self, id, users_name=None, group_name=None):
        try:
            identity = self.conn.identity
            user_role_id = identity.find_role(name_or_id="user").id
            admin_role_id = identity.find_role(name_or_id="admin").id
            admin_user_list = []
            admin_user_list = self.admin_users.split(',')
            for admin_user in admin_user_list:
                user_id = identity.find_user(name_or_id=admin_user).id
                self.keystone.roles.grant(admin_role_id,
                                          user=user_id,
                                          project=id)

            embed(globals(), locals())
            if (users_name == None):
                group_obj = identity.find_group(name_or_id=group_name)
                self.keystone.roles.grant(admin_role_id,
                                          group=group_id,
                                          project=id)
            elif (group_name == None):
                user_name_list = []
                user_name_list = users_name.split(',')
                for user_name in user_name_list:
                    user_id = identity.find_user(name_or_id=user_name).id
                    self.keystone.roles.grant(admin_role_id,
                                              user=user_id,
                                              project=id)
            else:
                logging.error('Insert_rule variable was not inputed')
                exit(1)
        except Exception, e:
            logging.error('While insert role' + str(e))
Example #16
0
 def __call__(self):
     try:
         from ptpython.repl import embed
         embed(globals(), None)
     except ImportError:
         printo('Install ptpython for a better repl')
         import code
         code.interact(banner="Launching strandard python repl", readfunc=None, local=globals())
def main():
    with ExitStack() as e:
        r = Robot()
        e.enter_context(r)
        # s = Server()
        # e.enter_context(s)
    # ws = Websocket()
        embed(globals(), locals())
Example #18
0
def shell():
    import sys
    from ptpython import repl
    from flask.globals import _app_ctx_stack

    app = _app_ctx_stack.top.app

    repl.embed(globals=app.make_shell_context())
Example #19
0
 def ptshell():
     """Use ptpython as shell."""
     try:
         from ptpython.repl import embed
         if not app.config['TESTING']:
             embed(app.make_shell_context())
     except ImportError:
         click.echo('ptpython not installed! Use the default shell instead.')
Example #20
0
def run():
    from .app import app

    parser = argparse.ArgumentParser(description='Nekoyume shell')
    args = parser.parse_args()

    app.app_context().push()
    embed(globals(), locals())
Example #21
0
 def start(self):
     try:
         from ptpython.repl import embed
     except ImportError:
         raise ShellNotAvailableError('PtPython shell not available.')
     print(self.banner)
     embed(globals=self.context, vi_mode=self.ptpy_vi_mode)
     return None
Example #22
0
def run() -> None:
    a = create_parser().parse_args()

    config_file, history_file = get_config_and_history_file(a)

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

    # --interactive
    if a.interactive and a.args:
        # Note that we shouldn't run PYTHONSTARTUP when -i is given.
        startup_paths = [a.args[0]]
        sys.argv = a.args

    # 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")
            # NOTE: We have to pass an empty dictionary as namespace. Omitting
            #       this argument causes imports to not be found. See issue #326.
            exec(code, {})

    # Run interactive shell.
    else:
        enable_deprecation_warnings()

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

            # Adjust colors if dark/light background flag has been given.
            if a.light_bg:
                repl.min_brightness = 0.0
                repl.max_brightness = 0.60
            elif a.dark_bg:
                repl.min_brightness = 0.60
                repl.max_brightness = 1.0

        import __main__

        embed(
            vi_mode=a.vi,
            history_filename=history_file,
            configure=configure,
            locals=__main__.__dict__,
            globals=__main__.__dict__,
            startup_paths=startup_paths,
            title="Python REPL (ptpython)",
        )
Example #23
0
def create_shell(console, manage_dict=None, extra_vars=None):
    """Creates the shell"""
    manage_dict = manage_dict or MANAGE_DICT
    _vars = globals()
    _vars.update(locals())
    auto_imported = import_objects(manage_dict)
    if extra_vars:
        auto_imported.update(extra_vars)
    _vars.update(auto_imported)
    msgs = []
    if manage_dict['shell']['banner']['enabled']:
        msgs.append(
            manage_dict['shell']['banner']['message'].format(**manage_dict))
    if auto_imported and manage_dict['shell']['auto_import']['display']:
        auto_imported_names = [
            key for key in auto_imported.keys()
            if key not in ['__builtins__', 'builtins']
        ]
        msgs.append('\tAuto imported: {0}\n'.format(auto_imported_names))

    banner_msg = u'\n'.join(msgs)

    exec_init(manage_dict, _vars)
    exec_init_script(manage_dict, _vars)

    if console == 'ptpython':
        try:
            from ptpython.repl import embed
            embed({}, _vars)
        except ImportError:
            click.echo("ptpython is not installed!")
        return

    if console == 'bpython':
        try:
            from bpython import embed
            embed(locals_=_vars, banner=banner_msg)
        except ImportError:
            click.echo("bpython is not installed!")
        return

    try:
        if console == 'ipython':
            from IPython import start_ipython
            from traitlets.config import Config
            c = Config()
            c.TerminalInteractiveShell.banner2 = banner_msg
            start_ipython(argv=[], user_ns=_vars, config=c)
        else:
            raise ImportError
    except ImportError:
        if manage_dict['shell']['readline_enabled']:
            import readline
            import rlcompleter
            readline.set_completer(rlcompleter.Completer(_vars).complete)
            readline.parse_and_bind('tab: complete')
        shell = code.InteractiveConsole(_vars)
        shell.interact(banner=banner_msg)
Example #24
0
 def do_interact(self, args):
     """
     Interact: start interpreter.
     (Override the 'pdb' implementation. We call ptpython instead.)
     """
     print('')
     ns = self.curframe.f_globals.copy()
     ns.update(self.curframe_locals)
     embed(globals=ns)
Example #25
0
 def run(self):
     ctx_vars = locals()
     ctx_vars['game'] = ctx_vars.pop('self').game
     try:
         from ptpython.repl import embed
         embed(locals=ctx_vars, vi_mode=False)
     except ImportError:
         from code import interact
         interact(local=ctx_vars)
Example #26
0
def repl():
    """
    Repl mode entry point. 
    Implies debug, check, and headful modes
    """
    projects = config.read_config_file()
    utlis.post('Scanner/repl', f"True", retain=True)
    embed(globals(), locals())
    utlis.post('Scanner/repl', f"False", retain=True)
Example #27
0
def main():
    pymod_exists('virtualenv', msg=(
        'Virtualenv is required for this bootstrap to run.\n'
        'Install virtualenv via:\n'
        '\t$ [sudo] pip install virtualenv'
    ), throw=True)

    pymod_exists('pip', msg=(
        'pip is required for this bootstrap to run.\n'
        'Find instructions on how to install at: %s' %
        'http://pip.readthedocs.org/en/latest/installing.html'
    ), throw=True)

    prompt_toolkit = Project(
        project_dir='~/study/python/python-prompt-toolkit/',
        virtualenv_dir='.venv/'
    )
    prompt_toolkit.setup()

    pyvim = Project(
        project_dir='~/study/python/pyvim',
        virtualenv_dir='.venv/',
    )
    pyvim.setup()
    pyvim.env.install(prompt_toolkit.project_dir, options=['-e'])


    ptpython = Project(
        project_dir='~/study/python/ptpython/',
        virtualenv_dir='.venv/'
    )
    ptpython.setup()
    ptpython.env.install(prompt_toolkit.project_dir, options=['-e'])

    ptpdb = Project(
        project_dir='~/study/python/ptpdb/',
        virtualenv_dir='.venv/'
    )
    ptpdb.setup()
    ptpdb.env.install(prompt_toolkit.project_dir, options=['-e'])

    pymux = Project(
        project_dir='~/study/python/pymux/',
        virtualenv_dir='.venv/'
    )
    pymux.setup()
    pymux.env.install(prompt_toolkit.project_dir, options=['-e'])

    pymux = Project(
        project_dir='~/work/python/profiling/',
        virtualenv_dir='.venv/'
    )
    pymux.setup()

    if os.environ.get('REPL', False):
        from ptpython.repl import embed
        embed(globals(), locals())
Example #28
0
def main() -> None:
    config_file, history_file = get_config_and_history_file(EverythingIsNone())

    parser = DefaultArgumentParser()
    parser.add_argument("--vi-mode", help="Vi mode", action="store_true")
    args = parser.parse_args()
    configure_logging_from_args(args)

    check_chain_dir()
    coinstate = read_chain_from_disk()
    wallet = open_or_init_wallet()
    thread = start_networking_peer_in_background(args, coinstate)
    thread.local_peer.show_stats()

    print("Starting REPL, exit with exit()")
    try:
        globals = {
            'thread': thread,
            'local_peer': thread.local_peer,
            'show_stats': thread.local_peer.show_stats,
            'wallet': wallet,
            'get_coinstate': lambda: thread.local_peer.chain_manager.coinstate,
            'SASHIMI_PER_COIN': SASHIMI_PER_COIN,
        }

        for module in [
                skepticoin.datatypes, skepticoin.networking.messages,
                skepticoin.signing, skepticoin.humans
        ]:
            for attr in module.__all__:  # type: ignore
                globals[attr] = getattr(module, attr)

        def configure(repl: PythonRepl) -> None:
            if os.path.exists(config_file):
                run_config(repl, config_file)
            else:
                # from https://github.com/prompt-toolkit/ptpython/blob/master/examples/ptpython_config/config.py
                # Ask for confirmation on exit.
                repl.confirm_exit = False

            # embedded in other applications.
            repl.title = "Skepticoin %s " % __version__

        embed(
            vi_mode=args.vi_mode,
            globals=globals,
            configure=configure,
            history_filename=history_file,
            patch_stdout=True,
        )

    finally:
        print("Stopping networking thread")
        thread.stop()
        print("Waiting for networking thread to stop")
        thread.join()
        print("Done; waiting for Python-exit")
Example #29
0
def main(source_dir, **options):
    """
    Extract metadata from Python source distributions
    """

    options = Munch(options)

    if options.color:
        cfg.logging.config.isatty = True
    configure_logging()

    dist = Distribution(req=Requirement.from_line(source_dir))
    for extra in options.extra:
        extra, req = extra.split(":")
        dist.add_requirement(req, extra=extra)

    if options.interactive:
        namespace = dict(
            Distribution=Distribution,
            Requirement=Requirement,
            dist=dist,
            dump=util.dump,
            dumps=util.dumps,
        )
        click.secho("distinfo shell %s:" % VERSION, fg="white", bold=True)
        cachedir = Path(appdirs.user_cache_dir("distinfo", "distinfo"))
        cachedir.mkdir(parents=True, exist_ok=True)
        repl.embed(
            namespace,
            configure=repl.run_config,
            history_filename=cachedir / "history",
        )
    else:
        if options.requires:
            obj = dist.requires
        else:
            obj = dist.metadata
            if options.include:
                obj = {
                    k: v
                    for k, v in obj.items() if k in options.include.split(",")
                }
            if options.exclude:
                obj = {
                    k: v
                    for k, v in obj.items()
                    if k not in options.exclude.split(",")
                }
        kwargs = Munch(fmt=options.fmt)
        if options.pretty and options.fmt == "json":
            kwargs.indent = 2
        dump = util.dumps(obj, **kwargs)
        if options.output:
            with open(options.output, "w") as stream:
                stream.write(dump)
        else:
            print(dump)
Example #30
0
 def launch_ptipython():
     imported_objects = get_launch_args(**options)
     history_filename = os.path.expanduser('~/.ptpython_history')
     embed(
         user_ns=imported_objects,
         history_filename=history_filename,
         vi_mode=vi_mode,
         configure=run_config,
     )
Example #31
0
def emb(globals, locals):
    conf_file = os.path.expanduser("~/.ptpython/config.py")
    if os.path.exists(conf_file):
        import importlib.util
        spec = importlib.util.spec_from_file_location("ptpython_conf", conf_file)
        ptpython_conf = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(ptpython_conf)

    embed(globals, locals, configure=ptpython_conf.configure)
Example #32
0
    def ptpython(self, options):
        history_filename = os.path.expanduser('~/.ptpython_history')

        # start the interpreter
        globals_dict = default_imports()
        locals_dict = {}
        embed(globals_dict,
              locals_dict,
              history_filename=history_filename,
              configure=run_config)
Example #33
0
def shell(env):
    '''Start a new interactive python session'''
    namespace = {'env': env}
    try:
        from ptpython.repl import embed
        hf = str(Path('~/.ptpython_history').expanduser())
        embed(namespace, history_filename=hf)
    except ImportError:
        from code import interact
        interact('', local=namespace)
Example #34
0
def shell(env):
    '''Start a new interactive python session'''
    namespace = {'env': env}
    try:
        from ptpython.repl import embed
        hf = str(Path('~/.ptpython_history').expanduser())
        embed(namespace, history_filename=hf)
    except ImportError:
        from code import interact
        interact('', local=namespace)
Example #35
0
    def run(self):
        print("Starting server console...")
        try:
            embed(globals(), locals())
            sys.exit(1)
        except Exception as e:
            print(f"This error happened on loading ptpython: {e}")
            print("Fallback to std_console")

        self.alter_console()
Example #36
0
def calculate_carbon(regional_report):
    for month, usage in regional_report.items():
        for usage_type, amount in usage.to_dict().items():
            if amount < 1:
                continue
            if usage_type.endswith('Bytes') and amount < 10**9:
                continue
            print(month, usage_type, amount)
    from ptpython.repl import embed
    embed(globals(), locals(), vi_mode=True)
Example #37
0
 def __call__(self):
     try:
         from ptpython.repl import embed
         embed(globals(), None)
     except ImportError:
         try:
             from IPython import embed
             embed()
         except ImportError:
             import code
             code.interact(banner="Launching standard python repl", readfunc=None, local=globals())
Example #38
0
 def __call__(self):
     try:
         from ptpython.repl import embed
         embed(globals(), None)
     except ImportError:
         try:
             from IPython import embed
             embed()
         except ImportError:
             import code
             code.interact(banner="Launching standard python repl", readfunc=None, local=globals())
Example #39
0
 def start(self) -> None:
     try:
         from bpython import embed
     except ImportError:
         raise ShellNotAvailableError("BPython shell not available.")
     if self.prompt:
         warnings.warn("Custom prompts not supported by BPythonShell.")
     if self.output:
         warnings.warn("Custom output templates not supported by BPythonShell.")
     embed(banner=self.banner, locals_=self.context)
     return None
Example #40
0
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)

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

    # --interactive
    if a['--interactive']:
        startup_paths.append(a['--interactive'])

    # 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'))

    # Run interactive shell.
    else:
        enable_deprecation_warnings()

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

        # Save user settings in config file when repl is done
        def done(repl):
            path = os.path.join(config_dir, 'conf.cfg')
            # Create the file if it doesn't exist
            repl.settings.save_config(path)

        embed(vi_mode=vi_mode,
              history_filename=os.path.join(config_dir, 'history'),
              configure=configure,
              done=done,
              startup_paths=startup_paths,
              title='Python REPL (ptpython)')
Example #41
0
 def postOptions(self):
     historyFile = os.path.expanduser(self['history-file'])
     if not embed:
         interp = code.InteractiveConsole(self.namespace(), '<axiom browser>')
         if readline is not None and os.path.exists(historyFile):
             readline.read_history_file(historyFile)
         try:
             interp.interact("%s.  Autocommit is off." % (str(axiom.version),))
         finally:
             if readline is not None:
                 readline.write_history_file(historyFile)
     else:
         embed(self.namespace(), None, None, False, historyFile, '<axiom browser>')
Example #42
0
def _embed_ptpython():
    """Embed a ptpython vanilla prompt."""
    try:
        from ptpython.repl import embed
    except ImportError:
        return False

    from inspect import currentframe
    caller = currentframe().f_back.f_back
    print(_embed_banner.format(filename=caller.f_code.co_filename,
                               line=caller.f_lineno))
    embed(caller.f_globals, caller.f_locals)
    return True
Example #43
0
File: cli.py Project: raj347/manage
def create_shell(ipython, ptpython, manage_dict=None, extra_vars=None):
    """Creates the shell"""
    manage_dict = manage_dict or MANAGE_DICT
    _vars = globals()
    _vars.update(locals())
    auto_imported = import_objects(manage_dict)
    if extra_vars:
        auto_imported.update(extra_vars)
    _vars.update(auto_imported)
    msgs = []
    if manage_dict['shell']['banner']['enabled']:
        msgs.append(
            manage_dict['shell']['banner']['message'].format(**manage_dict)
        )
    if auto_imported and manage_dict['shell']['auto_import']['display']:
        auto_imported_names = [
            key for key in auto_imported.keys()
            if key not in ['__builtins__', 'builtins']
        ]
        msgs.append('\tAuto imported: {0}\n'.format(auto_imported_names))

    banner_msg = u'\n'.join(msgs)

    if manage_dict['shell']['readline_enabled']:
        readline.set_completer(rlcompleter.Completer(_vars).complete)
        readline.parse_and_bind('tab: complete')

    exec_init(manage_dict, _vars)
    exec_init_script(manage_dict, _vars)

    if ptpython:
        try:
            from ptpython.repl import embed
            embed({}, _vars)
        except ImportError:
            click.echo("ptpython is not installed!")
        return

    try:
        if ipython is True:
            from IPython import start_ipython
            from traitlets.config import Config
            c = Config()
            c.TerminalInteractiveShell.banner2 = banner_msg
            start_ipython(argv=[], user_ns=_vars, config=c)
        else:
            raise ImportError
    except ImportError:
        shell = code.InteractiveConsole(_vars)
        shell.interact(banner=banner_msg)
Example #44
0
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)

    # 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>']

    # 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>']
        path = a['<arg>'][0]
        with open(path, 'rb') as f:
            code = compile(f.read(), path, 'exec')
            six.exec_(code)

    # Run interactive shell.
    else:
        enable_deprecation_warnings()

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

        import __main__
        embed(vi_mode=vi_mode,
              history_filename=os.path.join(config_dir, 'history'),
              configure=configure,
              locals=__main__.__dict__,
              globals=__main__.__dict__,
              startup_paths=startup_paths,
              title='Python REPL (ptpython)')
Example #45
0
File: reply.py Project: jalanb/pym
        def run_interactive_shell():

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

            from ptpython import repl
            repl.enable_deprecation_warnings()
            repl.embed(
                vi_mode=args.get('--vi', True),
                history_filename=os.path.join(args['config_dir'], 'history'),
                configure=configure,
                startup_paths=args.get('startup_paths', []),
                title=u'Pym REPL (pym)')
Example #46
0
 def start_shell(self):
     try:
         from ptpython.repl import embed
     except ImportError:
         log.error("Unable to start a shell: the ptpython module must be installed!")
         return
     yield from embed(globals(), locals(), return_asyncio_coroutine=True, patch_stdout=True, history_filename=".gns3_shell_history")
def ptipython_shell_runner(env, help):
    try:
        from ptpython.ipython import embed
    except ImportError:
        print('You need to install the ipython package for ptipython to work')
        return

    return embed(user_ns=env, banner2=help)
Example #48
0
    def start(self) -> None:
        try:
            from ptpython.ipython import embed
            from ptpython.repl import run_config
            from IPython.terminal.ipapp import load_default_config
        except ImportError:
            raise ShellNotAvailableError("PtIPython shell not available.")

        config_dir = Path("~/.ptpython/").expanduser()

        # Apply config file
        def configure(repl):
            path = config_dir / "config.py"
            if path.exists():
                run_config(repl, str(path))

        # Startup path
        startup_paths = []
        if "PYTHONSTARTUP" in os.environ:
            startup_paths.append(os.environ["PYTHONSTARTUP"])
        # exec scripts from startup paths
        for path in startup_paths:
            if Path(path).exists():
                with Path(path).open("rb") as f:
                    code = compile(f.read(), path, "exec")
                    exec(code, self.context, self.context)
            else:
                print(f"File not found: {path}\n\n")
                sys.exit(1)

        ipy_config = load_default_config()
        ipy_config.InteractiveShellEmbed = ipy_config.TerminalInteractiveShell
        ipy_config["InteractiveShellApp"]["extensions"] = self.ipy_extensions
        configure_ipython_prompt(ipy_config, prompt=self.prompt, output=self.output)
        embed(
            config=ipy_config,
            configure=configure,
            history_filename=config_dir / "history",
            user_ns=self.context,
            header=self.banner,
            vi_mode=self.ptpy_vi_mode,
        )
        return None
Example #49
0
def interactive_shell():
    """
    Coroutine that starts a Python REPL from which we can access the global
    counter variable.
    """
    print('You should be able to read and update the "counter[0]" variable from this shell.')
    yield from embed(globals=globals(), return_asyncio_coroutine=True, patch_stdout=True)

    # Stop the loop when quitting the repl. (Ctrl-D press.)
    loop.stop()
Example #50
0
    def start(self):
        coroutine = embed(self.namespace, self.namespace, title='Tin Bot Console',
                          patch_stdout=True, history_filename='.tin_bot_history',
                          return_asyncio_coroutine=True)

        # HACK: nasty hack to gain access to the command line interface wrapper
        self.cli = coroutine.gi_frame.f_locals['cli']

        future = asyncio.ensure_future(coroutine)
        return future
Example #51
0
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)

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

    # --interactive
    if a['--interactive']:
        startup_paths.append(a['--interactive'])

    # 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'))

    # Run interactive shell.
    else:
        enable_deprecation_warnings()

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

        embed(vi_mode=vi_mode,
              history_filename=os.path.join(config_dir, 'history'),
              configure=configure,
              startup_paths=startup_paths)
Example #52
0
    def start(self):
        self.running = True

        coroutine = embed(self.namespace, self.namespace, title='Jaspy Console',
                          patch_stdout=True, history_filename=self.history,
                          return_asyncio_coroutine=True)

        # HACK: nasty hack to gain access to the command line interface wrapper
        self.cli = coroutine.gi_frame.f_locals['cli']

        future = asyncio.ensure_future(coroutine)
        future.add_done_callback(self.on_closed)
        return future
def shell_command():
    """Runs an interactive Python shell in the context of a given
    Flask application.  The application will populate the default
    namespace of this shell according to its configuration.

    This is useful for executing small snippets of management code
    without having to manually configure the application.
    """
    from flask.globals import _app_ctx_stack
    from ptpython.repl import embed

    app = _app_ctx_stack.top.app
    ctx = {}

    # Support the regular Python interpreter startup script if someone
    # is using it.
    startup = os.environ.get('PYTHONSTARTUP')
    if startup and os.path.isfile(startup):
        with open(startup, 'r') as f:
            eval(compile(f.read(), startup, 'exec'), ctx)

    ctx.update(app.make_shell_context())

    embed(globals=ctx)
Example #54
0
File: shell.py Project: ADS101/odoo
 def bpython(self, local_vars):
     from bpython import embed
     embed(local_vars)
Example #55
0
File: shell.py Project: ADS101/odoo
 def ptpython(self, local_vars):
     from ptpython.repl import embed
     embed({}, local_vars)
    """
    repl.install_ui_colorscheme('my-colorscheme', _custom_ui_colorscheme)
    repl.use_ui_colorscheme('my-colorscheme')
    """

    # Add custom key binding for PDB.
    @repl.add_key_binding(Keys.ControlB)
    def _(event):
        ' Pressing Control-B will insert "pdb.set_trace()" '
        event.cli.current_buffer.insert_text('\nimport pdb; pdb.set_trace()\n')

    # Typing ControlE twice should also execute the current command.
    # (Alternative for Meta-Enter.)
    @repl.add_key_binding(Keys.ControlE, Keys.ControlE)
    def _(event):
        b = event.current_buffer
        if b.accept_action.is_returnable:
            b.accept_action.validate_and_handle(event.cli, b)


# Custom colorscheme for the UI. See `ptpython/layout.py` and
# `ptpython/style.py` for all possible tokens.
_custom_ui_colorscheme = {
    # Blue prompt.
    Token.Layout.Prompt:                          'bg:#eeeeff #000000 bold',

    # Make the status toolbar red.
    Token.Toolbar.Status:                         'bg:#ff0000 #000000',
}
embed(globals(), locals())
def ptpython_shell_runner(env, help):
    from ptpython.repl import embed

    print(help)
    return embed(locals=env)
Example #58
0
    def process_input(self, character):
        self.window.window.clear()
        if not self.searching and character in [80, 112]: # p/P to enter a python REPL
            try:                                          # You might need to
                import pprint                             # "sudo pip install ptpython"
                from ptpython.repl import embed           # to enable this feature.
                
                def configure(repl):
                    repl.prompt_style                   = "ipython"
                    repl.vi_mode                        = True
                    repl.confirm_exit                   = False
                    repl.show_status_bar                = False
                    repl.show_line_numbers              = True
                    repl.show_sidebar_help              = False
                    repl.highlight_matching_parenthesis = True
                    repl.use_code_colorscheme("native")

                def a(uid):
                    """
                    Return raw article text given an article uid.
                    """
                    response = self.window.c.get("articles/%s" % uid)
                    if response[1] == 200:
                        return response[0]['content']
                    return ""
                
                p = pprint.PrettyPrinter()
                p = p.pprint
                l = {"a": a, "c": self.window.c, "p": p, "window": self.window}
                reader  = self.window.get("reader")
                article = getattr(reader, "article", None)
                if article:
                    l['article'] = article

                self.window.stop()
                print("\n^D to exit.")
                embed(locals=l, configure=configure)
                self.window.start()
            except ImportError:
                pass

        if not self.searching and character == 47: # / to search
            articles = self.window.get("articles")
            articles.active = False
            self.searching = True
            return

        if self.searching:
            self.window.window.clear()
            if character == 23 and self.buffer:    # Clear buffer on ^W
                self.buffer = ''
            elif character == 263:                 # Handle backspace
                if self.buffer:
                    self.buffer = self.buffer[:-1]
                if not self.buffer:
                    self.searching = False
                    articles = self.window.get("articles")
                    articles.active = True

            elif character == 10 or character == 13:     # Handle the return key
                # Pass control back to the articles view
                self.searching = False
                articles = self.window.get("articles")
                articles.active = True
                reader   = self.window.get("reader")
                reader.active = False
                self.buffer = ""
            else:
                try: self.buffer += chr(character)     # Append input to buffer
                except: pass
                # Perform a search for what's in the current buffer.
                articles = self.window.get("articles")
                url = "articles/search/"+self.buffer+"?per_page=" + str(articles.height)
                (res, status) = self.window.c.get(url)
                if status == 200:
                    articles.fill_menu(res)
def main():
    embed(globals(), locals(), configure=configure)
Example #60
0
def main():
    embed(globals(), locals(), vi_mode=False)