Ejemplo n.º 1
0
def main():
    modules = []
    cmd = None  # Special
    args = {}
    general_args = args

    for arg in sys.argv[1:]:
        if arg.startswith("--"):
            # An option
            arg = arg[2:]
            if "=" in arg:
                k, v = arg.split("=", 1)
            else:
                if arg.startswith("no-"):
                    k = arg[3:]
                    v = False
                else:
                    k = arg
                    v = True
            k = k.replace("-", "_")
            args[k] = v
        else:
            cmd = arg
            args = {}
            modules.append((cmd, args))

    remaining = pre_options(**general_args)

    pymods = []
    for name, args in modules:
        m = launch_module(name, args)
        if not m:
            _fail("Could not launch all modules.")
            return
        pymods.append((name, m))

    post_options(**remaining)

    import sim.api
    sim.api.netvis.info = _netvis_welcome

    if sim.config.interactive:
        import code

        import sim.core as core
        import sim.basics as basics
        import topos as topo_package
        variables['start'] = core.world.start
        variables['sim'] = sys.modules['sim']
        variables['api'] = sim.api
        variables['topos'] = topo_package
        variables['basics'] = sim.basics
        for k, v in pymods:
            if "." in k:
                variables[k.rsplit(".")[-1]] = v
            variables[k.replace('.', '_')] = v
        if sim.config.readline:
            try:
                import readline
            except:
                pass
        interp = code.InteractiveConsole(locals=variables)
        interp.interact("")
    else:
        # Non-interactive always starts automatically
        import sim.core as core
        core.world.start(threaded=False)
        sys.exit(0 if core.error_counter.count == 0 else 1)
Ejemplo n.º 2
0
import code
import readline
import rlcompleter

import pyjsonrpc
cli = pyjsonrpc.HttpClient(url="http://localhost:9901/jsonrpc")

vars = globals()
vars.update(locals())
readline.set_completer(rlcompleter.Completer(vars).complete)
readline.parse_and_bind("tab: complete")
shell = code.InteractiveConsole(vars)
shell.interact()
Ejemplo n.º 3
0
def vte_child_routine(config):
    """
	This is the method which is executed within the child process spawned
	by VTE. It expects additional values to be set in the *config*
	object so it can initialize a new :py:class:`.KingPhisherRPCClient`
	instance. It will then drop into an interpreter where the user may directly
	interact with the rpc object.

	:param str config: A JSON encoded client configuration.
	"""
    config = serializers.JSON.loads(config)
    try:
        import readline
        import rlcompleter  # pylint: disable=unused-variable
    except ImportError:
        has_readline = False
    else:
        has_readline = True

    try:
        import IPython.terminal.embed
    except ImportError:
        has_ipython = False
    else:
        has_ipython = True

    for plugins_directory in ('rpc_plugins', 'rpc-plugins'):
        plugins_directory = find.data_directory(plugins_directory)
        if not plugins_directory:
            continue
        sys.path.append(plugins_directory)

    headers = config['rpc_data'].pop('headers')
    rpc = KingPhisherRPCClient(**config['rpc_data'])
    if rpc.headers is None:
        rpc.headers = {}
    for name, value in headers.items():
        rpc.headers[str(name)] = str(value)
    user_data_path = config['user_data_path']

    print("Python {0} on {1}".format(sys.version, sys.platform))  # pylint: disable=superfluous-parens
    print("Campaign Name: '{0}' ID: {1}".format(config['campaign_name'],
                                                config['campaign_id']))  # pylint: disable=superfluous-parens
    print(
        'The \'rpc\' object holds the connected KingPhisherRPCClient instance')
    console_vars = {
        'CAMPAIGN_NAME': config['campaign_name'],
        'CAMPAIGN_ID': config['campaign_id'],
        'os': os,
        'rpc': rpc,
        'sys': sys
    }

    if has_ipython:
        console = IPython.terminal.embed.InteractiveShellEmbed(
            ipython_dir=os.path.join(user_data_path, 'ipython'))
        console.register_magic_function(
            functools.partial(_magic_graphql, rpc, 'query'), 'line', 'graphql')
        console.register_magic_function(
            functools.partial(_magic_graphql, rpc, 'file'), 'line',
            'graphql_file')
        console.mainloop(console_vars)
    else:
        if has_readline:
            readline.parse_and_bind('tab: complete')
        console = code.InteractiveConsole(console_vars)
        for var in tuple(console_vars.keys()):
            console.push("__builtins__['{0}'] = {0}".format(var))
        console.interact('')
    return
Ejemplo n.º 4
0
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (self.parser.get_usage(), os.path.sep,
                                  config_file))
        else:
            config_file = self.args[0]

        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()
        locs = dict(__name__="pylons-admin")

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)

        # XXX: Note, initializing CONFIG here is Legacy support. pylons.config
        # will automatically be initialized and restored via the registry
        # restorer along with the other StackedObjectProxys
        # Load app config into paste.deploy to simulate request config
        # Setup the Paste CONFIG object, adding app_conf/global_conf for legacy
        # code
        conf = appconfig(config_name, relative_to=here_dir)
        conf.update(
            dict(app_conf=conf.local_conf, global_conf=conf.global_conf))
        paste.deploy.config.CONFIG.push_thread_config(conf)

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: \
            paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: \
            paste.registry.restorer.restoration_begin(request_id)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)

        # Determine the package name from the pylons.config object
        pkg_name = pylons.config['pylons.package']

        # Start the rest of our imports now that the app is loaded
        if is_minimal_template(pkg_name, True):
            model_module = None
            helpers_module = pkg_name + '.helpers'
            base_module = pkg_name + '.controllers'
        else:
            model_module = pkg_name + '.model'
            helpers_module = pkg_name + '.lib.helpers'
            base_module = pkg_name + '.lib.base'

        if model_module and can_import(model_module):
            locs['model'] = sys.modules[model_module]

        if can_import(helpers_module):
            locs['h'] = sys.modules[helpers_module]

        exec(
            'from pylons import app_globals, c, config, g, request, '
            'response, session, tmpl_context, url') in locs
        exec('from pylons.controllers.util import abort, redirect') in locs
        exec 'from pylons.i18n import _, ungettext, N_' in locs
        exec 'from pylons.templating import render' in locs

        # Import all objects from the base module
        __import__(base_module)

        base = sys.modules[base_module]
        base_public = [__name for __name in dir(base) if not \
                       __name.startswith('_') or __name == '_']
        locs.update((name, getattr(base, name)) for name in base_public)
        locs.update(dict(wsgiapp=wsgiapp, app=test_app))

        mapper = tresponse.config.get('routes.map')
        if mapper:
            locs['mapper'] = mapper

        banner = "  All objects from %s are available\n" % base_module
        banner += "  Additional Objects:\n"
        if mapper:
            banner += "  %-10s -  %s\n" % ('mapper', 'Routes mapper object')
        banner += "  %-10s -  %s\n" % ('wsgiapp',
                                       "This project's WSGI App instance")
        banner += "  %-10s -  %s\n" % ('app',
                                       'paste.fixture wrapped around wsgiapp')

        try:
            if self.options.disable_ipython:
                raise ImportError()

            # try to use IPython if possible
            from IPython.Shell import IPShellEmbed

            shell = IPShellEmbed(argv=self.args)
            shell.set_banner(shell.IP.BANNER + '\n\n' + banner)
            try:
                shell(local_ns=locs, global_ns={})
            finally:
                paste.registry.restorer.restoration_end()
        except ImportError:
            import code
            py_prefix = sys.platform.startswith('java') and 'J' or 'P'
            newbanner = "Pylons Interactive Shell\n%sython %s\n\n" % \
                (py_prefix, sys.version)
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass
            try:
                shell.interact(banner)
            finally:
                paste.registry.restorer.restoration_end()
Ejemplo n.º 5
0
# -*- coding: utf-8 -*-

import code
import readline
import rlcompleter

from app import app
from app import db

app.ready()

with app.app_context():
    try:
        exports = {'db': db}

        readline.set_completer(rlcompleter.Completer(exports).complete)
        readline.parse_and_bind("tab: complete")
        shell = code.InteractiveConsole(exports)
        shell.interact()
    finally:
        db.session.remove()
Ejemplo n.º 6
0
    def interact(self):
        """ Begin user interaction """

        import os
        history = self.history
        if history is True:
            history = ".pox_history"
        elif history:
            history = os.path.expanduser(history)
        if history:
            history = os.path.abspath(history)
            import readline, atexit
            _log = core.getLogger("py")
            try:
                readline.read_history_file(history)
                readline.set_history_length(10000)
                _log.debug("Read console history")
            except Exception:
                pass

            def save_history():
                readline.write_history_file(history)
                _log.debug("Saved console history")

            atexit.register(save_history)

        if self.completion:
            import readline, rlcompleter
            ns = globals().copy()
            ns.update(self.variables)
            # Note that things added to self.variables later won't be available.
            # To fix this, make a dict proxy that actually reads from self.variables
            # *and* globals().
            readline.set_completer(rlcompleter.Completer(ns).complete)
            readline.parse_and_bind("tab: complete")

        _monkeypatch_console()

        # print("This program comes with ABSOLUTELY NO WARRANTY.  This program " \
        #      "is free software,")
        # print("and you are welcome to redistribute it under certain conditions.")
        # print("Type 'help(pox.license)' for details.")

        # Ridiculously gross code to wait for a while before showing the console
        is_up = [False]

        def notify_up():
            is_up[0] = True

        core.call_later(notify_up)
        while not is_up[0]:
            time.sleep(0.2)
        if core._openflow_wanted:  # Hacky
            time.sleep(0.6)  # Long enough?
        else:
            time.sleep(0.2)

        if not core.running: return  # A race condition, but probably okay

        import code
        import sys
        sys.ps1 = "POX> "
        sys.ps2 = " ... "
        self.running = True

        console = code.InteractiveConsole(self.variables)

        # Patch in the synchronized feature
        real_runcode = console.runcode

        def runcode(code):
            if self.variables['sync'] and core.running:
                with core.scheduler.synchronized():
                    return real_runcode(code)
            return real_runcode(code)

        console.runcode = runcode

        # Patch in the event hook; why don't we just subclass InteractiveConsole?!
        real_runsource = console.runsource

        def runsource(source, *args, **kw):
            e = SourceEntered(source)
            self.raiseEvent(e)
            source = e.source
            if source is None: return
            return real_runsource(source, *args, **kw)

        console.runsource = runsource

        try:
            import readline
        except ImportError:
            pass
        console.interact('Ready.')

        self.running = False
        core.quit()
Ejemplo n.º 7
0
def user_input(local_vars):
    save_name = local_vars['exp_config'].save_name
    _banner = """
    ========================
    === ELEKTRONN2 SHELL ===
    ========================
    >> %s <<
    Shortcuts:
    'help' (display this help text),
    'q' (leave menu),         'kill'(saving last params),
    'sethist <int>',          'setlr <float>',
    'setmom <float>',         'setwd <float> (weight decay)
    'paramstats' ,            'gradstats',
    'actstats' (print statistics)
    'sf <nodename>' (show filters)',
    'load <filename>' (param files only, no model files),
    'preview' (produce preview predictions),
    'ip' (start embedded IPython shell)

    For everything else enter a command in the command line\n""" % (
        save_name, )

    _ipython_banner = """    You are now in the embedded IPython shell.
    You still have full access to the local scope of the ELEKTRONN2 shell
    (e.g. 'model', 'batch'), but shortcuts like 'q' no longer work.

    To leave the IPython shell and switch back to the ELEKTRONN2 shell, run
    'exit()' or hit 'Ctrl-D'."""

    print(_banner)
    data = local_vars['data']
    batch = local_vars['batch']
    trainer = local_vars['self']
    model = trainer.model
    exp_config = local_vars['exp_config']
    local_vars.update(locals())  # put the above into scope of console
    console = code.InteractiveConsole(locals=local_vars)

    while True:
        try:
            try:
                inp = prompt_toolkit.prompt(
                    u"%s@neuromancer: " % user_name,
                    # needs to be an explicit ustring for py2-compat
                    history=ptk_hist,
                    completer=NumaCompleter(lambda: local_vars,
                                            lambda: {},
                                            words=shortcut_completions,
                                            words_metastring='(shortcut)'),
                    auto_suggest=AutoSuggestFromHistory())
            # Catch all exceptions in order to prevent catastrophes in case ptk suddenly breaks
            except Exception:
                inp = console.raw_input("%s@neuromancer: " % user_name)
            logger.debug('(Shell received command "{}")'.format(inp))
            if inp == 'q':
                break
            elif inp == 'kill':
                break
            elif inp == 'help':
                print(_banner)
            elif inp == 'ip':
                try:
                    import IPython
                    IPython.embed(header=_ipython_banner)
                except ImportError:
                    print('IPython is not available. You will need to install '
                          'it to use this function.')
            elif inp.startswith('sethist'):
                i = int(inp.split()[1])
                exp_config.history_freq = i
            elif inp.startswith('setlr'):
                i = float(inp.split()[1])
                model.lr = i
            elif inp.startswith('setmom'):
                i = float(inp.split()[1])
                model.mom = i
            elif inp.startswith('setwd'):
                i = float(inp.split()[1])
                model.wd = i
            elif inp.startswith('sf'):
                try:
                    name = inp.split()[1]
                    w = model[name].w.get_value()
                    m = plotting.embedfilters(w)
                    with FileLock('plotting'):
                        plt.imsave('filters_%s.png' % name, m, cmap='gray')
                except:  # try to print filter of first Layer with w
                    for name, node in model.nodes.items():
                        if hasattr(node, 'w'):
                            m = plotting.embedfilters(node.w.get_value())
                            with FileLock('plotting'):
                                plt.imsave('filters.png', m, cmap='gray')
                            break

            elif inp == 'preview':
                try:
                    trainer.preview_slice(**exp_config.preview_kwargs)
                except Exception:
                    traceback.print_exc()
                    print(
                        '\n\nPlease check if/how you have configured previews '
                        'in your config file.\n(Look for "preview_data_path" '
                        'and "preview_kwargs" variables.)')
            elif inp == 'paramstats':
                model.paramstats()
            elif inp == 'gradstats':
                model.gradstats(*batch)
            elif inp == 'actstats':
                model.actstats(*batch)
            elif inp == 'debugbatch':
                trainer.debug_getcnnbatch()
            elif inp.startswith('load'):
                file_path = inp.split()[1]
                params = utils.pickleload(file_path)
                model.set_param_values(params)
            else:
                console.push(inp)

            plt.pause(0.00001)
        except KeyboardInterrupt:
            print(
                'Enter "q" to leave the shell and continue training.\n'
                'Enter "kill" to kill the training, saving current parameters.'
            )
        except IndexError as err:
            if any([
                    inp.startswith(shortcut)
                    for shortcut in shortcut_completions
            ]):  # ignore trailing spaces
                print(
                    'IndexError. Probably you forgot to type a value after the shortcut "{}".'
                    .format(inp))
            else:
                raise err  # All other IndexErrors are already correctly handled by the console.
        except ValueError as err:
            if any([
                    inp.startswith(shortcut)
                    for shortcut in shortcut_completions
            ]):  # ignore trailing spaces
                print(
                    'ValueError. The "{}" shortcut received an unexpected argument.'
                    .format(inp))
            else:
                raise err  # All other IndexErrors are already correctly handled by the console.
        except Exception:
            traceback.print_exc()
            print(
                '\n\nUnhandled exception occured. See above traceback for debug info.\n'
                'If you think this is a bug, please consider reporting it at '
                'https://github.com/ELEKTRONN/ELEKTRONN2/issues.')

    return inp
Ejemplo n.º 8
0
try:
    import readline
    import rlcompleter
    import atexit
    import os
    from os.path import expanduser
except ImportError:
    print "Python shell enhancement modules not available."
else:
    histfile = os.path.join(expanduser("~"), ".pythonhistory")
    import rlcompleter
    readline.parse_and_bind("tab: complete")
    if os.path.isfile(histfile):
        readline.read_history_file(histfile)
    atexit.register(readline.write_history_file, histfile)
    print "Python shell history and tab completion are enabled."

import code

ctx = globals()
ctx.update(locals())
code.InteractiveConsole(ctx).interact()
Ejemplo n.º 9
0
#!/usr/bin/env python

from .wikiscripts import *

if __name__ == '__main__':
    import code
    try:
        import readline, rlcompleter
    except:
        pass
    else:
        readline.parse_and_bind("tab: complete")
        banner += ' TAB completion available.'
    namespace = globals().copy()
    namespace.update(locals())
    code.InteractiveConsole(namespace).interact(banner)
Ejemplo n.º 10
0
def cli_loop(robot):
    global RUNNING, histfile, ans

    cli_globals = globals()
    cli_globals['world'] = robot.world
    cli_globals['light_cube'] = world.light_cube
    cli_globals['charger'] = robot.world.charger
    cli_globals['ans'] = None

    running_fsm = vector_fsm.program.running_fsm = \
        StateMachineProgram(cam_viewer=False, simple_cli_callback=simple_cli_callback)
    cli_globals['running_fsm'] = running_fsm
    running_fsm.start()

    cli_loop._console = code.InteractiveConsole()
    cli_loop.battery_warned = False
    while True:
        if not cli_loop.battery_warned and robot.get_battery_state(
        ).battery_level == 1:
            cli_loop.battery_warned = True
            print(
                "\n** Low battery. Type robot.behavior.drive_on_charger() to recharge."
            )
        elif cli_loop.battery_warned and robot.get_battery_state(
        ).battery_level == 2:
            cli_loop.battery_warned = False
        if RUNNING == False:
            return
        cli_loop._line = ''
        while cli_loop._line == '':
            readline.write_history_file(histfile)
            try:
                os_version = platform.system()
                if os_version == 'Darwin':  # Tkinter breaks console on Macs
                    print('VectorCLI>>> ', end='')
                    cli_loop._line = sys.stdin.readline().strip()
                else:
                    cli_loop._line = cli_loop._console.raw_input(
                        'VectorCLI>>> ').strip()
            except KeyboardInterrupt:
                process_interrupt()
                continue
            except EOFError:
                print("EOF.\nType 'exit' to exit.\n")
                continue
            try:
                robot.kine.get_pose()
            except:
                pass
        if cli_loop._line[0] == '!':
            do_shell_command(cli_loop._line[1:])
            continue
        elif cli_loop._line[0:3] == 'tm ' or cli_loop._line == 'tm':
            text_message(cli_loop._line[3:])
            continue
        elif cli_loop._line[0:5] == 'show ' or cli_loop._line == 'show':
            show_args = cli_loop._line[5:].split(' ')
            show_stuff(show_args)
            continue
        elif cli_loop._line[0:7] == 'reload ':
            do_reload(cli_loop._line[7:])
            continue
        elif cli_loop._line[0:6] == 'start ' or cli_loop._line == 'start':
            start_args = cli_loop._line[6:].split(' ')
            start_stuff(start_args)
            continue
        cli_loop._do_await = False
        if cli_loop._line[0:7] == 'import ' or cli_loop._line[0:5] == 'from '  or \
               cli_loop._line[0:7] == 'global ' or cli_loop._line[0:4] == 'del '   or \
               cli_loop._line[0:4] == 'for ' or \
               cli_loop._line[0:4] == 'def '    or cli_loop._line[0:6] == 'async ' :
            # Can't use assignment to capture a return value, so None.
            ans = None
        elif cli_loop._line[0:6] == 'await ':
            cli_loop._do_await = True
            cli_loop._line = 'ans=' + cli_loop._line[6:]
        elif cli_loop._line[0:5] == 'exit':
            # Clean up
            try:
                world_viewer.exited = True
            except:
                pass
            if running_fsm:
                running_fsm.stop()
            RUNNING = False
        else:
            cli_loop._line = 'ans=' + cli_loop._line
        try:
            cli_globals[
                'charger'] = robot.world.charger  # charger may have appeared
            exec(cli_loop._line, cli_globals)
            if cli_loop._do_await:
                print("Can't use await outside of an async def.")
                ans = None  # ans = await ans
            if not ans is None:
                print(ans, end='\n\n')
        except KeyboardInterrupt:
            print('Keyboard interrupt!')
            robot.disconnect()
        except SystemExit:
            print('Type exit() again to exit Python.')
            robot.disconnect()
            RUNNING = False
        except Exception:
            traceback.print_exc()
            print()
Ejemplo n.º 11
0
Archivo: cli.py Proyecto: scars321/theo
def start_repl(args):
    exploits = []

    # Transactions to frontrun
    if args.skip_mythril is False:
        print("Scanning for exploits in contract: {contract}".format(
            contract=args.contract))
        exploits += exploits_from_mythril(
            rpcHTTP=args.rpc_http,
            rpcWS=args.rpc_ws,
            rpcIPC=args.rpc_ipc,
            contract=args.contract,
            account_pk=args.account_pk,
            timeout=args.timeout,
        )
    if args.load_file != "":
        exploits += exploits_from_file(
            file=args.load_file,
            rpcHTTP=args.rpc_http,
            rpcWS=args.rpc_ws,
            rpcIPC=args.rpc_ipc,
            contract=args.contract,
            account_pk=args.account_pk,
            timeout=args.timeout,
        )

    if len(exploits) == 0:
        print("No exploits found. You're going to need to load some exploits.")
    else:
        print("")
        print("Found exploits(s):")
        print(exploits)

    # Add local tools for console
    w3 = Web3(
        Web3.HTTPProvider(args.rpc_http,
                          request_kwargs={"timeout": args.timeout}))
    from theo.exploit.exploit import Exploit
    from theo.exploit.tx import Tx

    # Imports for REPL
    import os, atexit, readline, rlcompleter

    # Load history
    history_path = os.path.join(os.environ["HOME"], ".theo_history")
    if os.path.isfile(history_path):
        readline.read_history_file(history_path)
    # Trigger history save on exit
    atexit.register(readline.write_history_file, history_path)
    # Load variables
    vars = globals()
    vars.update(locals())
    # Start REPL
    readline.set_completer(rlcompleter.Completer(vars).complete)
    readline.parse_and_bind("tab: complete")
    del os, atexit, readline, rlcompleter
    code.InteractiveConsole(vars).interact(banner="""
Tools available in the console:
- `exploits` is an array of loaded exploits found by Mythril or read from a file
- `w3` an initialized instance of web3py for the provided HTTP RPC endpoint
- `dump()` writing a json representation of an object to a local file

Check the readme for more info:
https://github.com/cleanunicorn/theo

Theo version {version}.

""".format(version=__version__))

    print("Shutting down")
Ejemplo n.º 12
0
def _EmbedCode(variables):
    import code  # pylint: disable=g-import-not-at-top
    code.InteractiveConsole(variables).interact()
Ejemplo n.º 13
0
import readline
import code
import rlcompleter

from dmx import *
from fixtures import *
from color import *
from effects import *

if __name__ == "__main__":
    washs = [Wash(1 + 29 * i) for i in range(8)]
    w = washs[1]
    w.color = Color(1, 0, 0)
    dmx = DMX(washs, [EffectHue(w)])
    # dmx = DMX(washs, [])
    dmx.start()

    readline.parse_and_bind("tab: complete")
    variables = globals().copy()
    variables.update(locals())
    shell = code.InteractiveConsole(variables)
    shell.interact()

    dmx.stop()
Ejemplo n.º 14
0
     import code
     import rlcompleter  # noqa
     import readline
     import atexit
     # history file
     histfile = os.path.join(os.environ['HOME'], '.history.python')
     try:
         readline.read_history_file(histfile)
     except IOError:
         pass
     atexit.register(readline.write_history_file, histfile)
     readline.parse_and_bind("tab: complete")
     sh = SmartHome()
     _sh_thread = threading.Thread(target=sh.start)
     _sh_thread.start()
     shell = code.InteractiveConsole(locals())
     shell.interact()
     exit(0)
 elif args.logics:
     reload_logics()
     exit(0)
 elif args.version:
     print("{0}".format(VERSION))
     exit(0)
 elif args.stop:
     lib.daemon.kill(__file__)
     exit(0)
 elif args.debug:
     MODE = 'debug'
 elif args.quiet:
     pass
Ejemplo n.º 15
0
def _EmbedCode(variables):
    code.InteractiveConsole(variables).interact()
Ejemplo n.º 16
0
    def closeDirectory(self):
        print('OUTER LOOP')
        while True:
            print('loop')
            print('-------------------------------')
            print('-1) Back')
            print(' 0) Home')
            print('-------------------------------')
            for idx, item in enumerate(self.items):
                print(' %s) %s' % (idx + 1, item[0]))
            try:
                print('')
                print("Enter Action Number")
                try:
                    action = raw_input()
                except:
                    action = input()
                sys.argv = ['', 0, None]
                try:
                    print(action)
                    action = int(action) - 1
                    if action == -2:
                        if len(self.history) > 0:
                            sys.argv = ['', 0, self.history.pop(-1)]
                            self.last_action = ''
                        return
                    elif action == -1:
                        sys.argv = ['', 0, '']
                    else:
                        print(self.items[action][1])
                        sys.argv = ['', 0, self.items[action][1]]

                except:
                    action = str(action)
                    get_context_check = re.findall(r'c(\d*)', action)

                    if len(get_context_check) == 1:
                        item = self.items[int(get_context_check[0]) - 1]
                        self.items = []
                        for context_item in item[0].cm:
                            self.items.append(
                                (context_item[0],
                                 re.findall(r'.*?\((.*?)\)',
                                            context_item[1])[0]))
                        continue

                    print('STRING ACTION')
                    print(action)
                    if action.startswith('action'):
                        try:
                            action = re.findall(r'action (.*?)$', action)[0]
                            sys.argv = ['', 0, action]
                        except:
                            print('failed')

                    elif action == 'shell':
                        print('RUN SHELL')
                        import code
                        variables = globals().copy()
                        variables.update(locals())
                        try:
                            shell = code.InteractiveConsole(variables)
                            shell.interact()
                        except:
                            self.items = []
                            self.history.append(self.last_action)
                            execfile(
                                os.path.abspath(
                                    os.path.join(os.getcwd(), 'seren.py')))

                    else:
                        raise Exception

                break
            except:
                import traceback
                traceback.print_exc()
                import time
                time.sleep(10)
                print('Please enter a valid entry')

        self.items = []
        if self.last_action != '':
            self.history.append(self.last_action)
            self.last_action = sys.argv[2]
        execfile(os.path.abspath(os.path.join(os.getcwd(), 'seren.py')))
Ejemplo n.º 17
0
#! -*- coding=utf8 -*-

#测试xmlrpcserver
'''
运行该程序可以跟simpy.py 程序进行交谈,可以调用simpy 里面定义的pow(),和hex()函数,这个就是远程调用了


'''

import xmlrpclib, code

url = "http://localhost:8765/"

s = xmlrpclib.ServerProxy(url)

interp = code.InteractiveConsole({'s': s})

interp.interact("you can now use the object to interact where the server")
Ejemplo n.º 18
0
def finalize(data, model=None, instance=None, results=None):
    """
    Perform final actions to finish the execution of the pyomo script.

    This function prints statistics related to the execution of the pyomo script.
    Additionally, this function will drop into the python interpreter if the `interactive`
    option is `True`.

    Required:
        model:      A pyomo model object.

    Optional:
        instance:   A problem instance derived from the model object.
        results:    Optimization results object.
    """
    #
    # Deactivate and delete plugins
    #
    ##import gc
    ##print "HERE - usermodel_plugins"
    ##_tmp = data.options._usermodel_plugins[0]
    cleanup()
    # NOTE: This function gets called for cleanup during exceptions
    #       to prevent memory leaks. Don't reconfigure the loggers
    #       here or we will lose the exception information.
    #configure_loggers(reset=True)
    data.local._usermodel_plugins = []
    ##gc.collect()
    ##print gc.get_referrers(_tmp)
    ##import pyomo.core.base.plugin
    ##print pyomo.common.plugin.interface_services[pyomo.core.base.plugin.IPyomoScriptSaveResults]
    ##print "HERE - usermodel_plugins"
    ##
    if not data.options.runtime.logging == 'quiet':
        sys.stdout.write('[%8.2f] Pyomo Finished\n' %
                         (time.time() - start_time))
        if (pympler_available is True) and (data.options.runtime.profile_memory
                                            >= 1):
            sys.stdout.write('Maximum memory used = %d bytes\n' %
                             data.local.max_memory)
        sys.stdout.flush()
    #
    model = model
    instance = instance
    results = results
    #
    if data.options.runtime.interactive:
        global IPython_available
        if IPython_available is None:
            try:
                import IPython
                IPython_available = True
            except:
                IPython_available = False

        if IPython_available:
            IPython.Shell.IPShellEmbed(
                [''],
                banner='\n# Dropping into Python interpreter',
                exit_msg='\n# Leaving Interpreter, back to Pyomo\n')()
        else:
            import code
            shell = code.InteractiveConsole(locals())
            print('\n# Dropping into Python interpreter')
            shell.interact()
            print('\n# Leaving Interpreter, back to Pyomo\n')
Ejemplo n.º 19
0
 def interact(self):
     """Opens up an interactive session with the current state of
     the console.
     """
     console = code.InteractiveConsole(self._frame)
     console.interact('# Interactive console. Type exit() to quit')
Ejemplo n.º 20
0
        link = self.dr.find_elements_by_id("Ca4gvo4bwg7400")
        print("学习新闻:")
        time.sleep(10)
        for i in range(0, self.NewsNum):
            print(link[i].text)
            link[i].click()
            time.sleep(10)
        MainPage = self.dr.current_window_handle
        AllPage = self.dr.window_handles
        # LearnPage = {}
        for i in AllPage:
            if i != MainPage:
                self.dr.switch_to_window(i)
                # LearnPage[i] = self.dr.execute_script('return document.body.scrollHeight')
                self.dr.execute_script(
                    'window.scrollTo(0, document.body.scrollHeight)')
        time.sleep(self.NewsTime * 60)

        interp.interact("")

    def quit(self):
        self.dr.quit()


if __name__ == "__main__":
    interp = code.InteractiveConsole(globals())
    # 每次打开6篇文章,打开4分钟
    zz = XueXiQiangGuo(6, 4)
    zz.login()
    zz.learn()
    # zz.quit()
Ejemplo n.º 21
0
def create_shell(console, manage_dict=None, extra_vars=None, exit_hooks=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)

    atexit_functions = [
        import_string(func_name) for func_name in
        manage_dict['shell'].get('exit_hooks', [])
    ]
    atexit_functions += exit_hooks or []
    for atexit_function in atexit_functions:
        atexit.register(atexit_function)

    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
            c.InteractiveShellApp.extensions = [
                extension for extension in
                manage_dict['shell'].get('ipython_extensions', [])
            ]
            c.InteractiveShellApp.exec_lines = [
                exec_line for exec_line in
                manage_dict['shell'].get('ipython_exec_lines', [])
            ]
            if manage_dict['shell'].get('ipython_auto_reload', True) is True:
                c.InteractiveShellApp.extensions.append('autoreload')
                c.InteractiveShellApp.exec_lines.append('%autoreload 2')
            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)
Ejemplo n.º 22
0
def load_and_run_shell() -> None:
    """Launch a shell for a thrift service."""
    sys.path.append(os.getcwd())

    parser = argparse.ArgumentParser(
        description=
        "Open a shell for a Thrift service with app configuration loaded.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    parser.add_argument("--debug",
                        action="store_true",
                        default=False,
                        help="enable extra-verbose debug logging")
    parser.add_argument(
        "--app-name",
        default="main",
        metavar="NAME",
        help="name of app to load from config_file (default: main)",
    )
    parser.add_argument("config_file",
                        type=argparse.FileType("r"),
                        help="path to a configuration file")

    args = parser.parse_args(sys.argv[1:])
    with args.config_file:
        config = read_config(args.config_file,
                             server_name=None,
                             app_name=args.app_name)
    logging.basicConfig(level=logging.INFO)

    env: Dict[str, Any] = {}
    env_banner = {
        "app": "This project's app instance",
        "context": "The context for this shell instance's span",
    }

    app = make_app(config.app)
    env["app"] = app

    baseplate: Baseplate = app.baseplate  # type: ignore
    context = baseplate.make_context_object()
    span = baseplate.make_server_span(context, "shell")
    env["context"] = span.context

    if config.shell and "setup" in config.shell:
        setup = _load_factory(config.shell["setup"])
        setup(env, env_banner)

    # generate banner text
    banner = "Available Objects:\n"
    for var in sorted(env_banner.keys()):
        banner += "\n  {:<12} {}".format(var, env_banner[var])

    try:
        # try to use IPython if possible
        from IPython import start_ipython

        try:
            # IPython 5.x+
            from traitlets.config.loader import Config
        except ImportError:
            # IPython 4 and below
            from IPython import Config

        ipython_config = Config()
        ipython_config.TerminalInteractiveShell.banner2 = banner
        start_ipython(argv=[], user_ns=env, config=ipython_config)
        raise SystemExit
    except ImportError:
        import code

        newbanner = f"Baseplate Interactive Shell\nPython {sys.version}\n\n"
        banner = newbanner + banner

        # import this just for its side-effects (of enabling nice keyboard
        # movement while editing text)
        try:
            import readline

            del readline
        except ImportError:
            pass

        shell = code.InteractiveConsole(locals=env)
        shell.interact(banner)
Ejemplo n.º 23
0
 def __init__(self):
     self.translator = PySwahili()
     self.block_keywords = list(self.translator.sw_to_en["block_keywords"].values())
     self.console = code.InteractiveConsole()
     self.intepreter = code.InteractiveInterpreter()
     self.newline = "\n"
Ejemplo n.º 24
0
def cmd_shell(opts, args):
    import code
    import readline  # NOQA
    code.InteractiveConsole(globals()).interact()
Ejemplo n.º 25
0
#! /usr/bin/env python
from BreakfastSerial import Button, Arduino

board = Arduino()
button = Button(board, 7)


def down_cb():
    print "button down"


def up_cb():
    print "button up"


button.down(down_cb)
button.up(up_cb)

# Run an interactive shell so you can play (not required)
import code
code.InteractiveConsole(locals=globals()).interact()
Ejemplo n.º 26
0
 def GoInteractive(self):
   _Session._InitReadline()
   code.InteractiveConsole(self._variables).interact(self._CreateBanner())
Ejemplo n.º 27
0
 def embed():
     vars = globals()
     vars.update(locals())
     shell = code.InteractiveConsole(vars)
     shell.interact()
Ejemplo n.º 28
0
 def new_console(self):
     return code.InteractiveConsole(locals={
         'app': self,
         '_': self.py['_'],
     },
                                    filename="<console>")
Ejemplo n.º 29
0
from flask import Flask, request, render_template, jsonify
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
import code
import io
import sys

app = Flask(__name__)
console = code.InteractiveConsole()
console.push('import sys')
prefix = ''


@app.route('/')
def home():
    return render_template('index.html')


@app.route('/exec/')
def run():
    if not request.args:
        return jsonify(error=True)
    if 'exec' in request.args.keys():
        global prefix
        global console
        command = request.args['exec']
        print(command)
        output = io.StringIO()
        old_stdout = sys.stdout
        old_stderr = sys.stderr
Ejemplo n.º 30
0
pos = [0,0]
orientation = 0
line, = plt.plot([],[], markersize=20)
plt.xlim([-10,10])
plt.ylim([-10,10])

def go(dist):
    global pos
    pos[0] += dist*cos(orientation*pi/180)
    pos[1] += dist*sin(orientation*pi/180)
    update_disp()

def spin(ang):
    global orientation
    orientation += ang
    update_disp()

def update_disp():
    line.set_marker((3,0,orientation-90))
    line.set_data(*pos)
    fig.canvas.draw()

update_disp()
plt.show(block=False)

ic = code.InteractiveConsole(locals=locals())
ic.interact()

class Robot:

    def __init__(self, pos = [0, 0], angle = 0, )