def remote_api_shell(auth_func, servername, appid, path, options, rpc_server_factory):
    """Actually run the remote_api_shell."""

    remote_api_stub.ConfigureRemoteApi(appid, path, auth_func,
                                       servername=servername,
                                       save_cookies=True, secure=options.secure,
                                       rpc_server_factory=rpc_server_factory)
    remote_api_stub.MaybeInvokeAuthentication()

    os.environ['SERVER_SOFTWARE'] = 'Development (remote_api_shell)/1.0'
    if not appid:
        appid = os.environ['APPLICATION_ID']
    sys.ps1 = '%s> ' % appid
    try:
        if options.bpython:
            from bpython import cli
            cli.main(args=[], banner=BANNER)
        elif options.ipython:
            import IPython
            # from IPython.config.loader import Config
            # Explicitly pass an empty list as arguments, because otherwise IPython
            # would use sys.argv from this script.
            #cfg = Config()
            #IPython.embed(config=cfg, banner2=BANNER)
            IPython.embed(banner2=BANNER)
        raise ImportError
    except ImportError:
        if readline is not None:
            readline.parse_and_bind('tab: complete')
            atexit.register(lambda: readline.write_history_file(HISTORY_PATH))
            if os.path.exists(HISTORY_PATH):
                readline.read_history_file(HISTORY_PATH)
        code.interact(banner=BANNER, local=globals())
Exemple #2
0
def bpython_curses():
    """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 it's 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 bpython.cli import main
    import bpython

    app = _app_ctx_stack.top.app
    banner = "Python %s on %s\nApp: %s [%s]\nInstance: %s" % (
        sys.version,
        sys.platform,
        app.import_name,
        app.env,
        app.instance_path,
    )
    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())

    main(banner=banner, locals_=ctx)
Exemple #3
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.cli import main
                main(['-i', '-q'], locals_=context, banner=self.banner)
                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)
Exemple #4
0
 def start(self) -> None:
     try:
         from bpython.cli import main
     except ImportError:
         raise ShellNotAvailableError("BPython Curses shell not available.")
     if self.prompt:
         warnings.warn("Custom prompts not supported by BPython Curses shell.")
     if self.output:
         warnings.warn(
             "Custom output templates not supported by BPython Curses shell."
         )
     main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
     return None
Exemple #5
0
 def start(self) -> None:
     try:
         from bpython.cli import main
     except ImportError:
         raise ShellNotAvailableError("BPython Curses shell not available.")
     if self.prompt:
         warnings.warn("Custom prompts not supported by BPython Curses shell.")
     if self.output:
         warnings.warn(
             "Custom output templates not supported by BPython Curses shell."
         )
     main(banner=self.banner, locals_=self.context, args=["-i", "-q"])
     return None
Exemple #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.cli import main
                main(['-i', '-q'], locals_=context, banner=self.banner)
                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)
from . import  msg
from . import socket

from .torrent import Torrent

t = Torrent('flagfromserver.torrent')
print t.info_hash

def connect():
    s = socket.socket()
    s.connect(('', 6882))
    s.send(str(msg.Handshake(info_hash=t.info_hash, peer_id='b'*20)))
    print s.getsockname(), 'connected to', s.getpeername()
    return s

from bpython import cli
cli.main(locals_=locals())
Exemple #8
0
 def run(self):
     client = self.client
     cli.main(locals_=locals())
Exemple #9
0
def repl():
    from bpython import cli; cli.main(locals_=locals())
Exemple #10
0
def embed(locals_=None, args=['-i', '-q'], banner=None):
    from bpython.cli import main
    return main(args, locals_, banner)
def bpython_shell(appid=None):
    from bpython import cli

    cli.main(args=[], banner=BANNER)
Exemple #12
0
def embed(locals_=None, args=['-i', '-q'], banner=None):
    from bpython.cli import main
    return main(args, locals_, banner)
Exemple #13
0
        elif args["deny"]:
            deny_config(config_file)

    mod = use_file(Path(args["--file"]) if args["--file"] else None)
    if hasattr(mod, "setup"):
        mod.setup()  # type: ignore

    if args["--name"]:
        if args["--name"] not in _config_registry:
            print_error(f'Invalid --name: "{args["--name"]}"')
            sys.exit(1)
        config_dict = _config_registry[args["--name"]]
        logger.debug(f'Using named config: "{args["--name"]}"')
        logger.debug(config_dict)
    else:
        config_dict = _cfg
    # Allow default shell to be overriden by command-line argument
    shell_name = args["--shell"]
    if shell_name:
        config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
    logger.debug(f"Starting with config {config_dict}")
    start(**config_dict)

    if hasattr(mod, "teardown"):
        mod.teardown()  # type: ignore
    sys.exit(0)


if __name__ == "__main__":
    main()
Exemple #14
0
def start_bpython_shell():
    from bpython import cli
    cli.main(args=[])
Exemple #15
0
        elif args["deny"]:
            deny_config(config_file)

    mod = use_file(Path(args["--file"]) if args["--file"] else None)
    if hasattr(mod, "setup"):
        mod.setup()  # type: ignore

    if args["--name"]:
        if args["--name"] not in _config_registry:
            print_error(f'Invalid --name: "{args["--name"]}"')
            sys.exit(1)
        config_dict = _config_registry[args["--name"]]
        logger.debug(f'Using named config: "{args["--name"]}"')
        logger.debug(config_dict)
    else:
        config_dict = _cfg
    # Allow default shell to be overriden by command-line argument
    shell_name = args["--shell"]
    if shell_name:
        config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
    logger.debug(f"Starting with config {config_dict}")
    start(**config_dict)

    if hasattr(mod, "teardown"):
        mod.teardown()  # type: ignore
    sys.exit(0)


if __name__ == "__main__":
    main()
Exemple #16
0
def embed(locals_=None, args=["-i", "-q"], banner=None):
    from bpython.cli import main

    return main(args, locals_, banner)
Exemple #17
0
    def handle_noargs(self, **options):
        # XXX: (Temporary) workaround for ticket #1796: force early loading of all
        # models from installed apps.
        from django.db.models.loading import get_models, get_apps
        loaded_models = get_models()

        use_plain = options.get('plain', False)

        from django.conf import settings
        imported_objects = {'settings': settings}

        import_messages = []
        for app_mod in get_apps():
            app_models = get_models(app_mod)
            if not app_models:
                continue
            model_labels = []
            for model in app_models:
                name = model.__name__
                while name in imported_objects:
                    name += '_'
                imported_objects[name] = model
                if model.__name__ == name:
                    model_labels.append(name)
                else:
                    model_labels.append("{} as {}".format(
                        model.__name__, name))
            import_messages.append(
                "Models from '%s': %s"
                "" %
                (app_mod.__name__.split('.')[-2], ", ".join(model_labels)))
        try:
            if use_plain:
                # Don't bother loading IPython, because the user wants plain
                # Python.
                raise ImportError
            try:
                from tempfile import mkstemp
                _, tmp_name = mkstemp(suffix='.py')
                tmp = open(tmp_name, 'w')

                try:
                    tmp.write("\n".join(
                        (('raise Warning, "%s"' if line.startswith("Failed")
                          else 'print "%s"') % line
                         for line in import_messages)))
                finally:
                    tmp.close()

                try:
                    from bpython import cli
                    cli.main(args=['--interactive', tmp_name],
                             locals_=imported_objects)
                finally:
                    os.unlink(tmp_name)
            except ImportError:
                try:
                    from IPython.frontend.terminal.embed import TerminalInteractiveShell
                    shell = TerminalInteractiveShell()
                    shell.mainloop()
                except ImportError:
                    # IPython < 0.11
                    # Explicitly pass an empty list as arguments, because otherwise
                    # IPython would use sys.argv from this script.
                    try:
                        from IPython.Shell import IPShell
                        shell = IPShell(argv=[])
                        shell.mainloop()
                    except ImportError:
                        # IPython not found at all, raise ImportError
                        raise
        except ImportError:
            import code
            # Set up a dictionary to serve as the environment for the shell, so
            # that tab completion works on objects that are imported at runtime.
            # See ticket 5082.
            for msg in import_messages:
                print msg
            try:  # Try activating rlcompleter, because it's handy.
                import readline
            except ImportError:
                pass
            else:
                # We don't have to wrap the following import in a 'try', because
                # we already know 'readline' was imported successfully.
                import rlcompleter
                readline.set_completer(
                    rlcompleter.Completer(imported_objects).complete)
                readline.parse_and_bind("tab:complete")

            # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow
            # system conventions and get $PYTHONSTARTUP first then import user.
            if not use_plain:
                pythonrc = os.environ.get("PYTHONSTARTUP")
                if pythonrc and os.path.isfile(pythonrc):
                    try:
                        execfile(pythonrc)
                    except NameError:
                        pass
                # This will import .pythonrc.py as a side-effect
                import user
            code.interact(local=imported_objects)
Exemple #18
0
 def bpython_shell():
     from bpython import cli
     cli.main(args=[], banner=banner, locals_=mods)
Exemple #19
0
def start_bpython_shell():
    from bpython import cli
    cli.main(args=[], locals_=starting_imports())
Exemple #20
0
    BANNER = "App Engine remote_api shell\n" + \
    "Python %s\n" % sys.version + \
    "The db, and memcache modules are imported."

    ## Use readline for completion/history if available
    try:
        import readline
    except ImportError:
        pass
    else:
        HISTORY_PATH = os.path.expanduser('~/.remote_api_shell_history')
        readline.parse_and_bind('tab: complete')
        if os.path.exists(HISTORY_PATH):
            readline.read_history_file(HISTORY_PATH)
        import atexit
        atexit.register(lambda: readline.write_history_file(HISTORY_PATH))

    sys.ps1 = '%s <-- ' % (host or APPID)

    #import code
    #code.interact(banner=BANNER, local=globals())

    #import models
    #from models import *
    from models.data import *
    #import IPython
    #IPython.Shell.IPShell(argv = [], user_ns=globals()).mainloop(sys_exit=1)
    from bpython import cli
    cli.main(args=[], locals_=globals(), banner=BANNER)
Exemple #21
0
    def handle_noargs(self, **options):
        # XXX: (Temporary) workaround for ticket #1796: force early loading of all
        # models from installed apps.
        from django.db.models.loading import get_models, get_apps
        loaded_models = get_models()

        use_plain = options.get('plain', False)

        from django.conf import settings
        imported_objects = {'settings': settings}

        import_messages = []
        for app_mod in get_apps():
            app_models = get_models(app_mod)
            if not app_models:
                continue
            model_labels = []
            for model in app_models:
                name = model.__name__
                while name in imported_objects:
                    name += '_'
                imported_objects[name] = model
                if model.__name__ == name:
                    model_labels.append(name)
                else:
                    model_labels.append("{} as {}".format(model.__name__, name))
            import_messages.append("Models from '%s': %s"
                "" % (app_mod.__name__.split('.')[-2], ", ".join(model_labels)))
        try:
            if use_plain:
                # Don't bother loading IPython, because the user wants plain
                # Python.
                raise ImportError
            try:
                from tempfile import mkstemp
                _, tmp_name = mkstemp(suffix='.py')
                tmp = open(tmp_name, 'w')

                try:
                    tmp.write("\n".join((('raise Warning, "%s"' if
                        line.startswith("Failed") else 'print "%s"') % line for
                        line in import_messages)))
                finally:
                    tmp.close()

                try:
                    from bpython import cli
                    cli.main(args=['--interactive', tmp_name],
                        locals_=imported_objects)
                finally:
                    os.unlink(tmp_name)
            except ImportError:
                try:
                    from IPython.frontend.terminal.embed import TerminalInteractiveShell
                    shell = TerminalInteractiveShell()
                    shell.mainloop()
                except ImportError:
                    # IPython < 0.11
                    # Explicitly pass an empty list as arguments, because otherwise
                    # IPython would use sys.argv from this script.
                    try:
                        from IPython.Shell import IPShell
                        shell = IPShell(argv=[])
                        shell.mainloop()
                    except ImportError:
                        # IPython not found at all, raise ImportError
                        raise
        except ImportError:
            import code
            # Set up a dictionary to serve as the environment for the shell, so
            # that tab completion works on objects that are imported at runtime.
            # See ticket 5082.
            for msg in import_messages:
                print msg
            try: # Try activating rlcompleter, because it's handy.
                import readline
            except ImportError:
                pass
            else:
                # We don't have to wrap the following import in a 'try', because
                # we already know 'readline' was imported successfully.
                import rlcompleter
                readline.set_completer(
                    rlcompleter.Completer(imported_objects).complete)
                readline.parse_and_bind("tab:complete")

            # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow
            # system conventions and get $PYTHONSTARTUP first then import user.
            if not use_plain:
                pythonrc = os.environ.get("PYTHONSTARTUP")
                if pythonrc and os.path.isfile(pythonrc):
                    try:
                        execfile(pythonrc)
                    except NameError:
                        pass
                # This will import .pythonrc.py as a side-effect
                import user
            code.interact(local=imported_objects)
Exemple #22
0
from . import msg
from . import socket

from .torrent import Torrent

t = Torrent('flagfromserver.torrent')
print t.info_hash


def connect():
    s = socket.socket()
    s.connect(('', 6882))
    s.send(str(msg.Handshake(info_hash=t.info_hash, peer_id='b' * 20)))
    print s.getsockname(), 'connected to', s.getpeername()
    return s


from bpython import cli
cli.main(locals_=locals())
Exemple #23
0
 def handle(self, **options):
     from django.db.models.loading import get_models
     from bpython import cli
     for model in get_models():
         exec "from %s import %s" % (model.__module__, model.__name__)
     cli.main(args=[], locals_=locals())