Python code.InteractiveConsole() Examples

The following are 30 code examples of code.InteractiveConsole(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module code , or try the search function .
Example #1
Source File: pundle.py    From pundler with BSD 2-Clause "Simplified" License 9 votes vote down vote up
def run_console(glob):
    import readline
    import rlcompleter
    import atexit
    import code

    history_path = os.path.expanduser("~/.python_history")

    def save_history(history_path=history_path):
        readline.write_history_file(history_path)
    if os.path.exists(history_path):
        readline.read_history_file(history_path)

    atexit.register(save_history)

    readline.set_completer(rlcompleter.Completer(glob).complete)
    readline.parse_and_bind("tab: complete")
    code.InteractiveConsole(locals=glob).interact() 
Example #2
Source File: backdoor.py    From satori with Apache License 2.0 8 votes vote down vote up
def _create_interactive_locals(self):
        # Create and return a *new* locals dictionary based on self.locals,
        # and set any new entries in it. (InteractiveConsole does not
        # copy its locals value)
        _locals = self.locals.copy()
        # __builtins__ may either be the __builtin__ module or
        # __builtin__.__dict__; in the latter case typing
        # locals() at the backdoor prompt spews out lots of
        # useless stuff
        try:
            import __builtin__
            _locals["__builtins__"] = __builtin__
        except ImportError:
            import builtins
            _locals["builtins"] = builtins
            _locals['__builtins__'] = builtins
        return _locals 
Example #3
Source File: radar_terminal.py    From artview with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def runCode(self):
        '''Use :py:func:`code.interact` to acess python terminal'''
        # separe in thread to avoid conflict with running Qt Application
        if self.Vradar.value is None:
            common.ShowWarning("No Radar linked, aborting!")
            return
        import threading
        env = LocalEnvoriment(self.Vradar)
        env["np"] = np
        env["pyart"] = pyart
        banner = ("\n\n"
            "## Interactive field manipulation console\n"
            "##\n"
            "## Work with fields are if they were numpy arrays.\n"
            "##\n"
            "## Call help() for more\n"
            )
        self.console = code.InteractiveConsole(env)
        self.thread = threading.Thread(
            target=self.console.interact,
            kwargs={'banner': banner},
            )
        self.thread.daemon=True
        self.thread.start()
        #self.isRunning = True 
Example #4
Source File: __main__.py    From panasonic-viera with MIT License 7 votes vote down vote up
def interact(self, locals=None):
        class LambdaConsole(code.InteractiveConsole):
            def runsource(code_console, source, filename=None, symbol=None):
                try:
                    self.runner.run(source)
                except SystemExit:
                    raise
                except:
                    code_console.showtraceback()
                return False

        try:
            import readline; readline
        except ImportError:
            pass

        ps1, ps2 = getattr(sys, 'ps1', None), getattr(sys, 'ps2', None)
        try:
            sys.ps1, sys.ps2 = self.ps1, self.ps2
            LambdaConsole(locals=locals, filename="<demo>").interact(banner='')
        finally:
            sys.ps1, sys.ps2 = ps1, ps2 
Example #5
Source File: backdoor.py    From satori with Apache License 2.0 7 votes vote down vote up
def handle(self, conn, address):
        """
        Interact with one remote user.

        .. versionchanged:: 1.1b2 Each connection gets its own
            ``locals`` dictionary. Previously they were shared in a
            potentially unsafe manner.
        """
        fobj = conn.makefile(mode="rw")
        fobj = _fileobject(conn, fobj, self.stderr)
        getcurrent()._fileobj = fobj

        getcurrent().switch_in()
        try:
            console = InteractiveConsole(self._create_interactive_locals())
            console.interact(banner=self.banner)
        except SystemExit:  # raised by quit()
            if hasattr(sys, 'exc_clear'): # py2
                sys.exc_clear()
        finally:
            conn.close()
            fobj.close() 
Example #6
Source File: shell.py    From pecan with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def invoke(cls, ns, banner):  # pragma: nocover
        """
        :param ns: local namespace
        :param banner: interactive shell startup banner

        Embed an interactive native python shell.
        """
        import code
        py_prefix = sys.platform.startswith('java') and 'J' or 'P'
        shell_banner = 'Pecan Interactive Shell\n%sython %s\n\n' % \
            (py_prefix, sys.version)
        shell = code.InteractiveConsole(locals=ns)
        try:
            import readline  # noqa
        except ImportError:
            pass
        shell.interact(shell_banner + banner) 
Example #7
Source File: shell.py    From python-libmaas with GNU Affero General Public License v3.0 7 votes vote down vote up
def _run_interactive(namespace, descriptions):
        # We at a fully interactive terminal — i.e. stdin AND stdout are
        # connected to the TTY — so display some introductory text...
        banner = ["{automagenta}Welcome to the MAAS shell.{/automagenta}"]
        if len(descriptions) > 0:
            banner += ["", "Predefined objects:", ""]
            wrap = textwrap.TextWrapper(60, "    ", "    ").wrap
            sortkey = lambda name: (name.casefold(), name)
            for name in sorted(descriptions, key=sortkey):
                banner.append("  {autoyellow}%s{/autoyellow}:" % name)
                banner.extend(wrap(descriptions[name]))
                banner.append("")
        for line in banner:
            print(colorized(line))
        # ... then start IPython, or the plain familiar Python REPL if
        # IPython is not installed.
        try:
            import IPython
        except ImportError:
            code.InteractiveConsole(namespace).interact(" ")
        else:
            IPython.start_ipython(argv=[], display_banner=False, user_ns=namespace) 
Example #8
Source File: chainer2onnx.py    From chainer-compiler with MIT License 7 votes vote down vote up
def __init__(self, classtype):
        # classtypeのmethod は持ってるが init は呼ばれてない、というobjectが必要になる。
        # ので、あえて parent のinit を呼ばない継承をする
        class Tmp(classtype):
            def __init__(_):
                pass

        # dprint('user defined class of',classtype)
        ch = Tmp()
        ch.__module__ = classtype.__module__

        # code.InteractiveConsole({'Tmp': Tmp,'v': ch}).interact()
        def f(args, kwargs, env):
            if not isinstance(classtype.__init__, type(str.__init__)):  # slot wrapper というものらしい
                User_Defined_Func_In_Link(
                    ch, classtype.__init__).call(args, kwargs, env)

            return ch

        self.init_wrapper = Func(f) 
Example #9
Source File: CLI.py    From pycopia with Apache License 2.0 7 votes vote down vote up
def python(self, argv):
        import code
        ns = self._get_ns()
        console = code.InteractiveConsole(ns)
        console.raw_input = self._ui.user_input
        try:
            saveps1, saveps2 = sys.ps1, sys.ps2
        except AttributeError:
            saveps1, saveps2 = ">>> ", "... "
        sys.ps1, sys.ps2 = "%%GPython%%N:%s> " % (self._obj.__class__.__name__,), "more> "
        if readline:
            oc = readline.get_completer()
            readline.set_completer(Completer(ns).complete)
        console.interact("You are now in Python. ^D exits.")
        if readline:
            readline.set_completer(oc)
        sys.ps1, sys.ps2 = saveps1, saveps2
        self._reset_scopes()


# This is needed to reset PagedIO so background events don't cause the pager to activate. 
Example #10
Source File: basic_stream.py    From twitter-monitor with MIT License 7 votes vote down vote up
def launch_debugger(frame, stream=None):
    """
    Interrupt running process, and provide a python prompt for
    interactive debugging.
    """

    d = {'_frame': frame}  # Allow access to frame object.
    d.update(frame.f_globals)  # Unless shadowed by global
    d.update(frame.f_locals)

    import code, traceback

    i = code.InteractiveConsole(d)
    message = "Signal received : entering python shell.\nTraceback:\n"
    message += ''.join(traceback.format_stack(frame))
    i.interact(message) 
Example #11
Source File: win_syscall.py    From mayhem with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def main():
	parser = argparse.ArgumentParser(description='win_syscall: Windows native system call utility', conflict_handler='resolve')
	parser.add_argument('-f', '--file', dest='syscall_file', action='store', type=argparse.FileType('r'), help='json file to load syscall data from')
	parser.add_argument('-o', '--os', dest='os_name', action='store', help='the windows version to load syscall data for')
	arguments = parser.parse_args()

	if platform.system() != 'Windows':
		print("[-] Incompatible platform '{0}'".format(platform.system()))
		return

	syscall_map = None
	if arguments.syscall_file and arguments.os_name:
		syscall_map = json.load(arguments.syscall_file)
		if not arguments.os_name in syscall_map:
			print("[-] Invalid os name '{0}'".format(arguments.os_name))
			return
		syscall_map = [arguments.os_name]
		print("[+] Loaded {0} syscall symbols".format(len(syscall_map)))
	syscall = windows.WindowsX86Syscall(syscall_map)
	print("[+] Allocated syscall stub at 0x{0:08x}".format(syscall.address))

	console = code.InteractiveConsole(dict(syscall=syscall))
	console.interact() 
Example #12
Source File: util.py    From dcos with Apache License 2.0 7 votes vote down vote up
def setup_thread_debugger():
    """Setup a thread debbuger for pytest session

    This function, based on http://stackoverflow.com/a/133384, is meant to
    add debugging facility to pytest that will allow to debug deadlock that
    may sometimes occur.
    """
    def debug(signal, frame):
        """Interrupt running process and provide a python prompt for
        interactive debugging."""
        d = {'_frame': frame}  # Allow access to frame object.
        d.update(frame.f_globals)  # Unless shadowed by global
        d.update(frame.f_locals)

        i = code.InteractiveConsole(d)
        message = "Signal received : entering python shell.\nTraceback:\n"
        message += ''.join(traceback.format_stack(frame))
        i.interact(message)

    signal.signal(signal.SIGUSR1, debug)  # Register handler 
Example #13
Source File: __main__.py    From uiautomator2 with MIT License 7 votes vote down vote up
def cmd_console(args):
    import code
    import platform

    d = u2.connect(args.serial)
    model = d.shell("getprop ro.product.model").output.strip()
    serial = d.serial
    try:
        import IPython
        from traitlets.config import get_config
        c = get_config()
        c.InteractiveShellEmbed.colors = "neutral"
        IPython.embed(config=c, header="IPython -- d.info is ready")
    except ImportError:
        _vars = globals().copy()
        _vars.update(locals())
        shell = code.InteractiveConsole(_vars)
        shell.interact(banner="Python: %s\nDevice: %s(%s)" %
                       (platform.python_version(), model, serial)) 
Example #14
Source File: main.py    From ctfscoreboard with Apache License 2.0 7 votes vote down vote up
def main(argv):
    if 'createdb' in argv:
        models.db.create_all()
    elif 'createdata' in argv:
        from scoreboard.tests import data
        models.db.create_all()
        data.create_all()
    elif 'shell' in argv:
        try:
            import IPython
            run_shell = IPython.embed
        except ImportError:
            import readline  # noqa: F401
            import code
            run_shell = code.InteractiveConsole().interact
        run_shell()
    else:
        wsgi.app.run(
                host='0.0.0.0', debug=True,
                port=wsgi.app.config.get('PORT', 9999)) 
Example #15
Source File: signal_trace.py    From luci-py with Apache License 2.0 7 votes vote down vote up
def _debug(_sig, frame):
  """Starts an interactive prompt in the main thread."""
  d = {'_frame': frame}
  d.update(frame.f_globals)
  d.update(frame.f_locals)
  try:
    # Enables arrows to work normally.
    # pylint: disable=unused-variable
    import readline
  except ImportError:
    pass
  msg = 'Signal received : entering python shell.\nTraceback:\n%s' % (''.join(
      traceback.format_stack(frame)))
  symbols = set(frame.f_locals.keys() + frame.f_globals.keys())
  msg += 'Symbols:\n%s' % '\n'.join('  ' + x for x in sorted(symbols))
  code.InteractiveConsole(d).interact(msg) 
Example #16
Source File: backdoor.py    From PhonePi_SampleServer with MIT License 7 votes vote down vote up
def _create_interactive_locals(self):
        # Create and return a *new* locals dictionary based on self.locals,
        # and set any new entries in it. (InteractiveConsole does not
        # copy its locals value)
        _locals = self.locals.copy()
        # __builtins__ may either be the __builtin__ module or
        # __builtin__.__dict__; in the latter case typing
        # locals() at the backdoor prompt spews out lots of
        # useless stuff
        try:
            import __builtin__
            _locals["__builtins__"] = __builtin__
        except ImportError:
            import builtins # pylint:disable=import-error
            _locals["builtins"] = builtins
            _locals['__builtins__'] = builtins
        return _locals 
Example #17
Source File: gmacpyutil.py    From macops with Apache License 2.0 7 votes vote down vote up
def InteractiveConsole():
  """Launch an interactive python shell."""
  # pylint: disable=g-import-not-at-top,unused-variable
  import code
  import readline
  # pylint: enable=g-import-not-at-top,unused-variable
  console = code.InteractiveConsole(dict(globals(), **locals()))
  console.interact('Interactive shell for %s' %
                   os.path.basename(sys.argv[0])) 
Example #18
Source File: links.py    From chainer-compiler with MIT License 7 votes vote down vote up
def __init__(self, ch):
        super(Link_Convolution2D, self).__init__(L.Convolution2D(None, None))

        # code.InteractiveConsole({'ch': ch}).interact()

        self.ksize = size2d(ch.ksize)
        self.stride = size2d(ch.stride)
        ps = size2d(ch.pad)
        self.pads = ps + ps

        if not (ch.b is None):
            # nobias = True の場合
            self.M = ch.b.shape[0]
            self.b = helper.make_tensor_value_info(
                '/b', TensorProto.FLOAT, [self.M])
        else:
            self.M = "TODO"
            self.b = None

        self.W = helper.make_tensor_value_info(
            '/W', TensorProto.FLOAT,
            [self.M, 'channel_size'] + list(self.ksize)) 
Example #19
Source File: CLI.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def python(self, argv):
        import code
        ns = self._get_ns()
        console = code.InteractiveConsole(ns)
        console.raw_input = self._ui.user_input
        try:
            saveps1, saveps2 = sys.ps1, sys.ps2
        except AttributeError:
            saveps1, saveps2 = ">>> ", "... "
        sys.ps1, sys.ps2 = "%%GPython%%N:%s> " % (self._obj.__class__.__name__,), "more> "
        if readline:
            oc = readline.get_completer()
            readline.set_completer(Completer(ns).complete)
        console.interact("You are now in Python. ^D exits.")
        if readline:
            readline.set_completer(oc)
        sys.ps1, sys.ps2 = saveps1, saveps2
        self._reset_scopes() 
Example #20
Source File: cmd2plus.py    From OpenTrader with GNU Lesser General Public License v3.0 6 votes vote down vote up
def do_py(self, arg):
        '''
        py <command>: Executes a Python command.
        py: Enters interactive Python mode.
        End with ``Ctrl-D`` (Unix) / ``Ctrl-Z`` (Windows), ``quit()``, ``exit()``.
        Non-python commands can be issued with ``cmd("your command")``.
        Run python code from external files with ``run("filename.py")``
        '''
        self.pystate['self'] = self
        arg = arg.parsed.raw[2:].strip()
        localvars = (self.locals_in_py and self.pystate) or {}
        interp = InteractiveConsole(locals=localvars)
        interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())')
        if arg.strip():
            interp.runcode(arg)
        else:
            def quit():
                raise EmbeddedConsoleExit
            def onecmd_plus_hooks(arg):
                return self.onecmd_plus_hooks(arg + '\n')
            def run(arg):
                try:
                    file = open(arg)
                    interp.runcode(file.read())
                    file.close()
                except IOError as e:
                    self.perror(e)
            self.pystate['quit'] = quit
            self.pystate['exit'] = quit
            self.pystate['cmd'] = onecmd_plus_hooks
            self.pystate['run'] = run
            try:
                cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
                keepstate = Statekeeper(sys, ('stdin','stdout'))
                sys.stdout = self.stdout
                sys.stdin = self.stdin
                interp.interact(banner= "Python %s on %s\n%s\n(%s)\n%s" %
                       (sys.version, sys.platform, cprt, self.__class__.__name__, self.do_py.__doc__))
            except EmbeddedConsoleExit:
                pass
            keepstate.restore() 
Example #21
Source File: __init__.py    From georef-ar-api with MIT License 5 votes vote down vote up
def georef_console():
    """Inicia una consola interactiva de Python con algunos módulos de
    georef-ar-api precargados para realizar pruebas rápidas.

    """
    import code
    with app.app_context():
        console = code.InteractiveConsole(locals=locals())
        console.push('import service')
        console.push('es = service.normalizer.get_elasticsearch()')
        console.interact() 
Example #22
Source File: cmd2.py    From ZEROScan with MIT License 5 votes vote down vote up
def do_py(self, arg):  
        '''
        py <command>: Executes a Python command.
        py: Enters interactive Python mode.
        End with ``Ctrl-D`` (Unix) / ``Ctrl-Z`` (Windows), ``quit()``, '`exit()``.
        Non-python commands can be issued with ``cmd("your command")``.
        Run python code from external files with ``run("filename.py")``
        '''
        self.pystate['self'] = self
        arg = arg.parsed.raw[2:].strip()
        localvars = (self.locals_in_py and self.pystate) or {}
        interp = InteractiveConsole(locals=localvars)
        interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())')
        if arg.strip():
            interp.runcode(arg)
        else:
            def quit():
                raise EmbeddedConsoleExit
            def onecmd_plus_hooks(arg):
                return self.onecmd_plus_hooks(arg + '\n')
            def run(arg):
                try:
                    file = open(arg)
                    interp.runcode(file.read())
                    file.close()
                except IOError as e:
                    self.perror(e)
            self.pystate['quit'] = quit
            self.pystate['exit'] = quit
            self.pystate['cmd'] = onecmd_plus_hooks
            self.pystate['run'] = run
            try:
                cprt = 'Type "help", "copyright", "credits" or "license" for more information.'        
                keepstate = Statekeeper(sys, ('stdin','stdout'))
                sys.stdout = self.stdout
                sys.stdin = self.stdin
                interp.interact(banner= "Python %s on %s\n%s\n(%s)\n%s" %
                       (sys.version, sys.platform, cprt, self.__class__.__name__, self.do_py.__doc__))
            except EmbeddedConsoleExit:
                pass
            keepstate.restore() 
Example #23
Source File: rexec.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def runcode(self, co):
                self.locals['__builtins__'] = r.modules['__builtin__']
                r.s_apply(code.InteractiveConsole.runcode, (self, co)) 
Example #24
Source File: server.py    From opcua-modeling-tool with MIT License 5 votes vote down vote up
def embed():
        vars = globals()
        vars.update(locals())
        shell = code.InteractiveConsole(vars)
        shell.interact() 
Example #25
Source File: axiom_plugins.py    From axiom with MIT License 5 votes vote down vote up
def runcode(self, code):
        """
        Override L{code.InteractiveConsole.runcode} to run the code in a
        transaction unless the local C{autocommit} is currently set to a true
        value.
        """
        if not self.locals.get('autocommit', None):
            return self.locals['db'].transact(code.InteractiveConsole.runcode, self, code)
        return code.InteractiveConsole.runcode(self, code) 
Example #26
Source File: client-example.py    From opcua-modeling-tool with MIT License 5 votes vote down vote up
def embed():
        vars = globals()
        vars.update(locals())
        shell = code.InteractiveConsole(vars)
        shell.interact() 
Example #27
Source File: server-callback.py    From opcua-modeling-tool with MIT License 5 votes vote down vote up
def embed():
        vars = globals()
        vars.update(locals())
        shell = code.InteractiveConsole(vars)
        shell.interact() 
Example #28
Source File: server-enum.py    From opcua-modeling-tool with MIT License 5 votes vote down vote up
def embed():
        vars = globals()
        vars.update(locals())
        shell = code.InteractiveConsole(vars)
        shell.interact() 
Example #29
Source File: cli.py    From anthem with GNU Lesser General Public License v3.0 5 votes vote down vote up
def run(odoo_args, target, options):
    with Context(odoo_args, options) as ctx:
        mod_name, func_name = target.split('::')
        module = importlib.import_module(mod_name)
        func = getattr(module, func_name)
        func(ctx)
        if options.interactive:
            console = code.InteractiveConsole(locals={'ctx': ctx})
            import rlcompleter  # noqa
            import readline
            readline.parse_and_bind("tab: complete")
            console.interact(banner=banner())
        ctx.env.cr.commit() 
Example #30
Source File: server-example.py    From opcua-modeling-tool with MIT License 5 votes vote down vote up
def embed():
        vars = globals()
        vars.update(locals())
        shell = code.InteractiveConsole(vars)
        shell.interact()