Esempio n. 1
0
def pudb_shell(_globals, _locals):
    """
    This example shell runs a classic Python shell. It is based on
    run_classic_shell in pudb.shell.

    """
    # Many shells only let you pass in a single locals dictionary, rather than
    # separate globals and locals dictionaries. In this case, you can use
    # pudb.shell.SetPropagatingDict to automatically merge the two into a
    # single dictionary. It does this in such a way that assignments propogate
    # to _locals, so that when the debugger is at the module level, variables
    # can be reassigned in the shell.
    from pudb.shell import SetPropagatingDict
    ns = SetPropagatingDict([_locals, _globals], _locals)

    try:
        import readline
        import rlcompleter
        HAVE_READLINE = True
    except ImportError:
        HAVE_READLINE = False

    if HAVE_READLINE:
        readline.set_completer(
                rlcompleter.Completer(ns).complete)
        readline.parse_and_bind("tab: complete")
        readline.clear_history()

    from code import InteractiveConsole
    cons = InteractiveConsole(ns)
    cons.interact("Press Ctrl-D to return to the debugger")
Esempio n. 2
0
 def interact(self):
     old_raw_input = __builtin__.raw_input
     old_displayhook = sys.displayhook
     old_excepthook = sys.excepthook
     old_stdin = sys.stdin
     old_stdout = sys.stdout
     old_stderr = sys.stderr
     old_help = __builtin__.help
     old_quit = __builtin__.quit
     __builtin__.raw_input = self.raw_input
     __builtin__.help = "Close window to exit."
     __builtin__.quit = "Close window to exit."
     sys.displayhook = self.displayhook
     sys.excepthook = self.excepthook
     sys.stdin = self.pipe.stdin
     sys.stdout = self.pipe.stdout
     sys.stderr = self.pipe.stderr
     try:
         self.pipe.expect('RemoteConsole.initialize', repr(sys.version_info), sys.executable, os.getpid())
         InteractiveConsole.interact(self)
     finally:
         __builtin__.raw_input = old_raw_input
         __builtin__.help = old_help
         __builtin__.quit = old_quit
         sys.displayhook = old_displayhook
         sys.excepthook = old_excepthook
         sys.stdin = old_stdin
         sys.stdout = old_stdout
         sys.stderr = old_stderr
Esempio n. 3
0
 def __init__(self, engine):
     self.engine = engine
     self._stdout = sys.stdout
     self._ibuffer = [] #Parts of a statement
     self._obuffer = [] #Lines of output
     self.user_tracker = {}
     InteractiveConsole.__init__(self, {'engine': self.engine})
Esempio n. 4
0
def myshell():
    shell = InteractiveConsole()
    try:
        while 1:
            line = shell.raw_input(ps1)
            while 1:
                result = shell.push(line)
                if not result: break
                line = shell.raw_input(ps2)
    except:
        pass
    return
    def get_output(self): sys.stdout = self.cache
    def return_output(self): sys.stdout = self.stdout

    def push(self,line):
        self.get_output()
        # you can filter input here by doing something like
        # line = filter(line)
        InteractiveConsole.push(self,line)
        self.return_output()
        output = self.cache.flush()
        # you can filter the output here by doing something like
        # output = filter(output)
        print output # or do something else with it
        return 
def __main__(path=".", script=None, **flags):
    if not script:
        import os
        if os.path.isfile(path):
            path, script = ".", path
    env = dict(__utils)
    if flags.get('log',False):
        store = LogicalLogStore(path)
        env['logs'] = store
    else:
        store = GraphDatabaseStore(path)
        env['store'] = store
    if script:
        with open(script) as script:
            store.initialize()
            try:
                exec(script.read(), env)
            finally:
                store.shutdown()
    else:
        from code import InteractiveConsole
        console = InteractiveConsole(locals=env)
        store.initialize()
        try:
            console.interact(
                banner="Neo4j Store introspection console (Python)")
        finally:
            store.shutdown()
Esempio n. 6
0
 def interact(self):
     """Starts an InteractiveConsole."""
     sys.stdout = sys.__stdout__
     console = InteractiveConsole(locals=self.frame)
     console.interact('# Interactive console.'
                      ' Type exit() to quit')
     sys.stdout = logger
Esempio n. 7
0
class ClassicPythonShell(Shell, ConsoleProgressBarMixin):
    """Classic Python shell interface.

    This class allows igraph to be embedded in Python's shell."""
    
    def __init__(self):
        """Constructor.

        Imports Python's classic shell"""
        Shell.__init__(self)
        self._shell = None

        try:
            self.__class__.progress_bar = ProgressBar(TerminalController())
        except ValueError:
            # Terminal is not capable enough, disable progress handler
            del self.__class__._progress_handler

    def __call__(self):
        """Starts the embedded shell."""
        if self._shell is None:
            from code import InteractiveConsole
            self._shell = InteractiveConsole()
            print >> sys.stderr, "igraph %s running inside " % __version__,
            self._shell.runsource("from igraph import *")

        self._shell.interact()
Esempio n. 8
0
def run_script(intro=None, local=None, script_file=None, quit=True, show_script=True, raise_relax_error=False):
    """Python interpreter emulation.

    This function replaces 'code.interact'.


    @param intro:               The string to print prior to jumping to the prompt mode.
    @type intro:                str
    @param local:               A namespace which will become that of the prompt (i.e. the namespace
                                visible to the user when in the prompt mode).  This should be the
                                output of a function such as locals().
    @type local:                dict
    @param script_file:         The script file to be executed.
    @type script_file:          None or str
    @param quit:                If true, the default, then relax will exit after running the script.
    @type quit:                 bool
    @param show_script:         If true, the relax will print the script contents prior to executing
                                the script.
    @type show_script:          bool
    @param raise_relax_error:   If false, the default, then a nice error message will be sent to
                                STDERR, without a traceback, when a RelaxError occurs.  This is to
                                make things nicer for the user.
    @type raise_relax_error:    bool
    """

    # Replace the 'InteractiveConsole.interact' and 'InteractiveConsole.runcode' functions.
    InteractiveConsole.interact = interact_script
    InteractiveConsole.runcode = runcode

    # The console.
    console = InteractiveConsole(local)
    return console.interact(intro, local, script_file, quit, show_script=show_script, raise_relax_error=raise_relax_error)
 def push(self, line):
     if line.strip() == 'help':
         # Write some Cheshire3 help
         self.write("Cheshire3 Documentation can be found in the `docs` "
                    "folder of the distribution\n"
                    "or online at:\n"
                    "http://cheshire3.org/docs/\n")
         self.write("Type help() for Python's interactive help, or "
                    "help(object) for help about object.\n")
         return
     elif line.strip() == 'copyright':
         # Write Cheshire3 copyright info, before that of Python
         self.write('Cheshire3 is Copyright (c) 2005-2012, the University '
                    'of Liverpool.\n')
         self.write('All rights reserved.\n\n')
     elif line.strip() == "license":
         self.write(cheshire3_license() + '\n\n')
         self.write("Type marc_utils_license() for marc_utils license\n")
         self.write("Type python_license() for Python license\n")
     elif line.strip() == "license()":
         self.write(cheshire3_license_text() + '\n')
         return
     elif line.strip() == "marc_utils_license()":
         self.write(marc_utils_license() + '\n')
         return
     elif line.strip() == "python_license()":
         return InteractiveConsole.push(self, "license()")
     return InteractiveConsole.push(self, line)
Esempio n. 10
0
class PythonConsole(pudding.control.Console):
	""" an interactive python console for pudding """

	def __init__(self, parent=None, lokals=None, **kwargs):
		pudding.control.Console.__init__(self, parent, initial='', **kwargs)

		self.interpreter = InteractiveConsole(lokals)
		self.interpreter.write = self.write

		self.stdout = sys.stdout
		sys.stdout = self

	def on_return(self):
		""" run the command if its complete """
		self.input_buffer.append(self.input.value)

		self.write(">>> %s\n" % self.input.value)
		self.interpreter.push(self.input.value)

		self.input.clear()

	def write(self, string):
		""" write method to pretend to be a file like object """
		self.output.label += "%s" % string
		print >>self.stdout, string
Esempio n. 11
0
    def handle(self, conn, _address): # pylint: disable=method-hidden
        """
        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())
            if sys.version_info[:3] >= (3, 6, 0):
                # Beginning in 3.6, the console likes to print "now exiting <class>"
                # but probably our socket is already closed, so this just causes problems.
                console.interact(banner=self.banner, exitmsg='') # pylint:disable=unexpected-keyword-arg
            else:
                console.interact(banner=self.banner)
        except SystemExit:  # raised by quit()
            if hasattr(sys, 'exc_clear'): # py2
                sys.exc_clear()
        finally:
            conn.close()
            fobj.close()
Esempio n. 12
0
 def __init__(self):
     InteractiveConsole.__init__(self,
         locals={'exit': ExitWrapper(), 'help': HelpWrapper()})
     self.stdout = sys.stdout
     self.stderr = sys.stderr
     self._cache = Cache()
     self.output = ''
Esempio n. 13
0
 def handle(self, args):
     context = globals().copy()
     context.update(locals())
     readline.set_completer(rlcompleter.Completer(context).complete)
     readline.parse_and_bind('tab: complete')
     shell = InteractiveConsole(context)
     shell.interact()
Esempio n. 14
0
 def __init__(self):
     self.stdout = sys.stdout
     self.stderr = sys.stderr
     self.stdout_cacher = FileCacher()
     self.stderr_cacher = FileCacher()
     InteractiveConsole.__init__(self)
     return
Esempio n. 15
0
    def push(self, line):
        if self.inQuery:
            if self.hasDeclEnd(line):
                self.inQuery= False
                more = InteractiveConsole.push(self, line)
                return more
            elif line.find("`") >= 0:
                exc = 'Traceback (most recent call last):\n' + \
                      '  File "<stdin>", line 1, in <module>\n' + \
                      '  Cannot have both Python code and SociaLite query in one line\n'
                print exc
                self.buffer = []
                self.inQuery = False
                return False
            else:
                if line.strip():
                    self.buffer.append(line)
                return True
        else:
            if self.hasDeclBegin(line) and not self.hasDeclEnd(line):
                self.inQuery = True
                self.buffer.append(line)
                return True

        more = InteractiveConsole.push(self, line)
        return more
Esempio n. 16
0
 def _run(self):
     try:
         console = InteractiveConsole(self.locals)
         console.interact()
     finally:
         self.switch_out()
         self.finalize()
Esempio n. 17
0
def interactive_client(file, host, port, cache_size, readonly, repair,
                       startup):
    if file:
        storage = FileStorage(file, readonly=readonly, repair=repair)
        description = file
    else:
        wait_for_server(host, port)
        storage = ClientStorage(host=host, port=port)
        description = "%s:%s" % (host, port)
    connection = Connection(storage, cache_size=cache_size)
    namespace = {'connection': connection,
                 'root': connection.get(0),
                 'get': connection.get,
                 'sys': sys,
                 'os': os,
                 'p64': p64,
                 'u64': u64,
                 'pp': pprint}
    configure_readline(namespace, os.path.expanduser("~/.durushistory"))
    console = InteractiveConsole(namespace)
    if startup:
        console.runsource('execfile("%s")' % os.path.expanduser(startup))
    help = ('    connection -> the connection\n'
            '    root       -> get(0)\n'
            '    get(oid)   -> get an object\n'
            '    pp(object) -> pretty-print')
    console.interact('Durus (%s)\n%s' % (description, help))
Esempio n. 18
0
def _embed_vanilla():
    """
    Embed vanilla python interpreter (two frames back).

    This function is adapted from a StackOverflow answer by user "Havok", which
    you can find here: <http://stackoverflow.com/a/28423594>.
    """
    from code import InteractiveConsole
    from inspect import currentframe

    caller = currentframe().f_back.f_back

    env = {}
    env.update(caller.f_globals)
    env.update(caller.f_locals)

    try:
        import readline
        import rlcompleter
        readline.set_completer(rlcompleter.Completer(env).complete)
        readline.parse_and_bind("tab: complete")
    except ImportError:
        pass

    shell = InteractiveConsole(env)
    shell.interact(
        _embed_banner.format(
            filename=caller.f_code.co_filename, line=caller.f_lineno
        )
    )

    return True
Esempio n. 19
0
    def __init__(self, config):

        self.config = config

        try:
            import readline
        except ImportError as e:
            print(e)
        else:
            import rlcompleter

        startupfile = os.environ.get("PYTHONSTARTUP")
        if startupfile:
            execfile(startupfile, {}, {})

        proj_meta = config.project_metadata
        if proj_meta:
            package = proj_meta.get("package", None)

            sys.ps1 = "[%s]>>> " % package
            sys.ps2 = "[%s]... " % package

            self.prompt = package

        InteractiveConsole.__init__(self, locals=self.get_locals())
Esempio n. 20
0
def interactive_client(file, address, cache_size, readonly, repair,
                       startup):
    if file:
        storage = FileStorage(file, readonly=readonly, repair=repair)
        description = file
    else:
        socket_address = SocketAddress.new(address)
        wait_for_server(address=socket_address)
        storage = ClientStorage(address=socket_address)
        description = socket_address
    connection = Connection(storage, cache_size=cache_size)
    console_module = ModuleType('__console__')
    sys.modules['__console__'] = console_module
    namespace = {'connection': connection,
                 'root': connection.get_root(),
                 'get': connection.get,
                 'sys': sys,
                 'os': os,
                 'int8_to_str': int8_to_str,
                 'str_to_int8': str_to_int8,
                 'pp': pprint}
    vars(console_module).update(namespace)
    configure_readline(
        vars(console_module), os.path.expanduser("~/.durushistory"))
    console = InteractiveConsole(vars(console_module))
    if startup:
        src = '''with open('{fn}', 'rb') as _:
                     _ = compile(_.read(), '{fn}', 'exec')
                     exec(globals().pop('_'))
        '''.format(fn = os.path.expanduser(startup)).rstrip()
        console.runsource(src, '-stub-', 'exec')
    help = ('    connection -> the Connection\n'
            '    root       -> the root instance')
    console.interact('Durus %s\n%s' % (description, help))
Esempio n. 21
0
    def __init__(self, commands_module=None):
        import readline
        InteractiveConsole.__init__(self, globals())
        self.public_methods = ('pyex', 'quit', 'exit', 'help', 'menu') 
        self.hidden_actions = filter(lambda m: not m in self.public_methods, 
                                     dir(self) )
        self.hidden_actions.extend(dir(InteractiveConsole()))# DO NOT CHANGE THIS LINE!
        self.prompt = 'kusp>'
        self.banner = \
"""
================================================
KUSP Abstract Interactive Console

Type `help' for commands or `help <command>' 
for extended help about particular commands.
================================================
"""
        if commands_module is None:
            return

        from types import MethodType, FunctionType
        __import__(commands_module) 
        extra_commands = sys.modules[commands_module]
        c_filter = lambda name: not name.startswith("_") and \
                                type(getattr(extra_commands, name)) is FunctionType
 
        console_actions = filter( c_filter, dir(extra_commands))

        for action in console_actions:
            console_method = MethodType(getattr(extra_commands, action), self, self.__class__)
            setattr(self, action, console_method)
Esempio n. 22
0
    def __init__(self, locals=None, filename="<console>"):
        InteractiveConsole.__init__(self, locals, filename)

        # history consists of list of pairs [(FLAG, record), ...]
        # flag is IN_FLAG or OUT_FLAG
        # record a string containing history line
        self.history = []
Esempio n. 23
0
def run_classic_shell(locals, globals, first_time):
    if first_time:
        banner = "Hit Ctrl-D to return to PuDB."
    else:
        banner = ""

    ns = SetPropagatingDict([locals, globals], locals)

    from pudb.settings import get_save_config_path
    from os.path import join
    hist_file = join(
            get_save_config_path(),
            "shell-history")

    if HAVE_READLINE:
        readline.set_completer(
                rlcompleter.Completer(ns).complete)
        readline.parse_and_bind("tab: complete")
        try:
            readline.read_history_file(hist_file)
        except IOError:
            pass

    from code import InteractiveConsole
    cons = InteractiveConsole(ns)

    cons.interact(banner)

    if HAVE_READLINE:
        readline.write_history_file(hist_file)
Esempio n. 24
0
    def __init__(self, main):
        # Redirect stdout and stderr to our own write() function
        main.app.PythonConsole.write = main.app.PythonConsole.stream
        sys.stdout = main.app.PythonConsole
        sys.stderr = main.app.PythonConsole
        
        locals = {
            "__name__":   "__console__",
            "__doc__":    None,
            "main":       main,
            "PicoGUI":    PicoGUI,
            "sys":        sys,
            }
        InteractiveConsole.__init__(self,locals)

        try:
            sys.ps1
        except AttributeError:
            sys.ps1 = ">>> "
        try:
            sys.ps2
        except AttributeError:
            sys.ps2 = "... "

        self.main = main
        self.prompt = sys.ps1
        main.app.PythonPrompt.text = self.prompt
        main.app.link(self.enterLine, main.app.PythonCommand, 'activate')

        print "Python %s on %s\n(Widget Foundry shell, See main.__dict__ for useful variables)\n" %\
              (sys.version, sys.platform)
Esempio n. 25
0
def main():
    '''
    The main entry point
    '''
    salt_vars = get_salt_vars()

    def salt_outputter(value):
        '''
        Use Salt's outputters to print values to the shell
        '''
        if value is not None:
            try:
                import __builtin__
                __builtin__._ = value
            except ImportError:
                __builtins__._ = value

            salt.output.display_output(value, '', salt_vars['__opts__'])

    sys.displayhook = salt_outputter

    # Set maximum number of items that will be written to the history file
    readline.set_history_length(300)

    if os.path.exists(HISTFILE):
        readline.read_history_file(HISTFILE)

    atexit.register(savehist)
    atexit.register(lambda: sys.stdout.write('Salt you later!\n'))

    saltrepl = InteractiveConsole(locals=salt_vars)
    saltrepl.interact(banner=__doc__)
Esempio n. 26
0
    def __init__(self, host, client_port, server, exec_queue):
        BaseInterpreterInterface.__init__(self, server, exec_queue)
        self.client_port = client_port
        self.host = host
        try:
            import pydevd  # @UnresolvedImport
            if pydevd.GetGlobalDebugger() is None:
                raise RuntimeError()  # Work as if the debugger does not exist as it's not connected.
        except:
            ns = globals()
        else:
            # Adapted from the code in pydevd
            # patch provided by: Scott Schlesier - when script is run, it does not
            # pretend pydevconsole is not the main module, and
            # convince the file to be debugged that it was loaded as main
            sys.modules['pydevconsole'] = sys.modules['__main__']
            sys.modules['pydevconsole'].__name__ = 'pydevconsole'

            from imp import new_module
            m = new_module('__main__')
            sys.modules['__main__'] = m
            ns = m.__dict__
            try:
                ns['__builtins__'] = __builtins__
            except NameError:
                pass  # Not there on Jython...
        InteractiveConsole.__init__(self, ns)
        self._input_error_printed = False
Esempio n. 27
0
 def interact(self, banner=None):
     try:
         InteractiveConsole.interact(self, banner)
     except KeyboardInterrupt:
         if self.inQuery: 
             self.inQuery = False
             self.buffer = []
         print "Enter quit() or Ctrl-D to exit"
Esempio n. 28
0
 def __init__(self, *args, **kwds):
     # interactive console is an old-style class
     InteractiveConsole.__init__(self, *args, **kwds)
     import sys
     sys.ps1 = 'cython> '
     sys.ps2 = '.   ... '
     self._pyxbuild_dir = kwds.get('pyxbuild_dir', None)
     self.py_compile = self.compile
Esempio n. 29
0
def processMenu(inp, objId, s):
    if inp == "2":
        showPlayers()
    elif inp == "1":
        return setCurrentObject()
    elif inp == "7":
        giveTechs(objId)
    elif inp == "6":
        giveTech(objId)
    elif inp == "4":
        advanceLevel(objId)
    elif inp == "3":
        showGalaxies()
    elif inp == "5":
        promoteToImperator(objId)
    elif inp == "8":
        giveStratRes(objId)
    elif inp == "9":
        finishProdQueue(objId)
    elif inp == "10":
        createGalaxy()
    elif inp == "11":
        startGalaxy()
    elif inp == "12":
        deleteGalaxy()
    elif inp == "13":
        initDevelTesting(objID)
    elif inp == "14":
        giveFame(objID)
    elif string.upper(inp) == "I":
        showObj(objID)
    elif string.upper(inp) == "R":
        processTurns()
    elif string.upper(inp) == "T":
        s.processTurn()
    elif string.upper(inp) == "C":
        console = InteractiveConsole(locals())
        console.interact()
    elif string.upper(inp) == "CLEANUPFLEETS":
        console = cleanupBadFleets()

    return objId
Esempio n. 30
0
def run_commandloop(args):
    while 1:
        cmdline = raw_input("rr> ").strip()

        if cmdline:
            try:
                cmdargs = shlex.split(cmdline)
            except ValueError: # problem parsing line
                print "Cmdline syntax error"
                continue
                
            if cmdargs[0] in ('quit', 'exit'):
                sys.exit(0)

            if cmdargs[0] in ('help', '?'):
                print HELP_MESSAGE
                continue

            if cmdargs[0] == 'debug':
                import pdb
                pdb.set_trace()
                continue

            if cmdargs[0] == 'python':
                from code import InteractiveConsole
                ic = InteractiveConsole(locals=locals())
                ic.interact("Python Debug shell")
                continue
                
            if cmdargs[0] == 'test':
                # ok we have some cmdline arguments
                args = cmdargs[1:]
                break

            else:
                print "Unknown command.  Type 'help' for help."

        else:
            print "rr> test " + shlex_join(args)
            break

    return args
Esempio n. 31
0
def shell(locals=None, globals=None):
    from inspect import currentframe, getouterframes
    calling_frame = getouterframes(currentframe())[1][0]

    if locals is None:
        locals = calling_frame.f_locals
    if globals is None:
        globals = calling_frame.f_globals

    ns = SetPropagatingDict([locals, globals], locals)

    if HAVE_READLINE:
        readline.set_completer(
                rlcompleter.Completer(ns).complete)

    from code import InteractiveConsole
    cons = InteractiveConsole(ns)
    cons.interact("")

    readline.write_history_file(get_shell_hist_filename())
Esempio n. 32
0
    def python(self):
        from code import interact, InteractiveConsole

        try:
            import readline
            import rlcompleter
            readline.set_completer(rlcompleter.Completer(self.ns).complete)
            readline.parse_and_bind('tab:complete')
        except:
            pass

        console = InteractiveConsole(locals=self.ns)
        if self.cmd:
            console.runcode(self.cmd)
        elif self.script:
            console.runcode(open(self.script).read())
            if self.interact:
                console.interact(banner='')
        else:
            console.interact(banner=self.banner)
Esempio n. 33
0
 def raw_input(self, *args):
     line = InteractiveConsole.raw_input(self, *args)
     if line == EDIT_CMD:
         fd, tmpfl = mkstemp()
         os.write(fd, '\n'.join(self.last_buffer))
         os.close(fd)
         os.system('%s %s' % (EDITOR, tmpfl))
         line = open(tmpfl).read()
         os.unlink(tmpfl)
         tmpfl = ''
     return line
Esempio n. 34
0
def simple_repl(user_ns={}):
    if iswindows:
        setup_pyreadline()
    else:
        try:
            import rlcompleter  # noqa
            import readline  # noqa
            readline.parse_and_bind("tab: complete")
        except ImportError:
            pass

    user_ns = user_ns or {}
    import sys, re  # noqa
    for x in ('os', 'sys', 're'):
        user_ns[x] = user_ns.get(x, globals().get(x, locals().get(x)))
    user_ns['exit'] = Exit()
    user_ns['help'] = Helper()
    from code import InteractiveConsole
    console = InteractiveConsole(user_ns)
    console.interact(BANNER + 'Use exit to quit')
Esempio n. 35
0
def debug_breakpoint():
    """
    Python debug breakpoint.
    """
    from code import InteractiveConsole
    from inspect import currentframe

    caller = currentframe().f_back

    env = {}
    env.update(caller.f_globals)
    env.update(caller.f_locals)

    shell = InteractiveConsole(env)
    shell.interact(
        '* Break: {} ::: Line {}\n'
        '* Continue with Ctrl+D or raise SystemExit...'.format(
            caller.f_code.co_filename, caller.f_lineno
        )
    )
Esempio n. 36
0
    def __init__(self, localsEnv=globals()):
        InteractiveConsole.__init__(self, localsEnv)
        errcount = 1
        while errcount:
            try:
                logger.debug("customConsoleClass", localsEnv)
                break
            except BlockingIOError as be:
                if errcount > 5:
                    raise
                else:
                    errcount += 1
        self.consoleLocals = localsEnv

        # catch the output of the interactive interpreter
        self.stdout = sys.stdout
        self.stderr = sys.stderr
        self.cache = OutputFilter()

        self.help()
Esempio n. 37
0
File: exec.py Progetto: wkta/tsunami
    def __init__(self, pere):
        """Constructeur du contexte"""
        Contexte.__init__(self, pere)
        self.opts.prompt_prf = ""
        self.opts.prompt_clr = ""
        self.opts.nl = False
        self.evenement = Evenement(None, "exec")
        self.test = Test(self.evenement)
        variables = self.test.get_globales(self.evenement)
        self.console = InteractiveConsole(variables)
        self.py_prompt = ">>> "

        if pere:
            variables = self.evenement.espaces.variables
            joueur = pere.joueur
            salle = joueur.salle
            variables.update({
                "joueur": joueur,
                "salle": salle,
            })
Esempio n. 38
0
 def push(self, line):
     try:
         more = InteractiveConsole.push(self, line)
     except KeyboardInterrupt:
         self.write('\nKeyboardInterrupt\n')
         self.resetbuffer()
         more = False
     if more:
         self.write(self.ps2)
     else:
         self.write(self.ps1)
Esempio n. 39
0
    def configure(self, attrs=None):
        # *attrs* is a list of attribute names that the user wants to
        # configure. This defaults to all the non-private names
        if attrs is None:
            attrs = [n for n in dir(self) if not n.startswith('_')]

        # set message displayed when the interactive console starts
        msg1 = ('Python ' + sys.version + ' on ' + sys.platform + '\n'
                'Type "help", "copyright", "credits" or "license" for '
                'more information.')
        msg2 = ('The current namespace has been populated with the '
                'following attributes from the class instance:')
        msg3 = ', '.join(['"%s"' % i for i in attrs])
        msg4 = ('The values associate with these names can be modified, '
                'and the attributes of the class instance will be '
                'updated with the new values. When finished, exit the '
                'interpreter with Ctrl+"d".')

        banner = '\n'
        banner += msg1
        banner += '\n\n'
        banner += '\n'.join(wrap(msg2, 70))
        banner += '\n\n'
        banner += '\n    '.join(wrap('    ' + msg3, 66))
        banner += '\n\n'
        banner += '\n'.join(wrap(msg4, 70))
        banner += '\n'
        namespace = {}

        for n in attrs:
            # fill the namespace with deep copies of the classes current
            # attributes
            namespace[n] = getattr(self, n)

        # set the attribute values with an interactive console
        ic = InteractiveConsole(locals=namespace)
        ic.interact(banner=banner)
        # namespace has been modified in the interactive console. Give the
        # instance the new values
        for n in attrs:
            setattr(self, n, namespace[n])
Esempio n. 40
0
    def runsource(self, source, filename="<input>", symbol="single"):
        """
        THis function ...
        :param source:
        :param filename:
        :param symbol:
        :return:
        """

        #if self.remote is not None:
        #if self.remote_session is not None:
        if self.locals["session"] is not None:

            if "Frame.from_file" in source:

                variable_name = source.split("=")[0].strip()

                #print(variable_name)

                #print(source.split("Frame(")[1])

                arguments = source.split("from_file(")[1].split(")")[0].split(
                    ",")

                path = arguments[0]

                #print(arguments)

                source = variable_name + " = RemoteFrame.from_file(" + path + ", session)"

                #print(source)

            #source = source.replace("Image.from_file(", "RemoteImage")
            #source = source.replace("DataCube.from_file", "RemoteDataCube")
            #print(source)

        # Run the code
        InteractiveConsole.runsource(self,
                                     source,
                                     filename=filename,
                                     symbol=symbol)
Esempio n. 41
0
 def runcode(self, code):
     """
     Overrides and captures stdout and stdin from
     InteractiveConsole.
     """
     sys.stdout = self.stream
     sys.stderr = self.stream
     sys.excepthook = sys.__excepthook__
     result = InteractiveConsole.runcode(self, code)
     sys.stdout = sys.__stdout__
     sys.stderr = sys.__stderr__
     return result
Esempio n. 42
0
 def __init__(self,
              host,
              client_port,
              mainThread,
              connect_status_queue=None):
     BaseInterpreterInterface.__init__(self, mainThread,
                                       connect_status_queue)
     self.client_port = client_port
     self.host = host
     self.namespace = {}
     self.interpreter = InteractiveConsole(self.namespace)
     self._input_error_printed = False
Esempio n. 43
0
def prompt(intro=None, local=None):
    """Python interpreter emulation.

    This function replaces 'code.interact'.


    @param intro:   The string to print prior to jumping to the prompt mode.
    @type intro:    str
    @param local:   A namespace which will become that of the prompt (i.e. the namespace visible to
                    the user when in the prompt mode).  This should be the output of a function such
                    as locals().
    @type local:    dict
    """

    # Replace the 'InteractiveConsole.interact' and 'InteractiveConsole.runcode' functions.
    InteractiveConsole.interact = interact_prompt
    InteractiveConsole.runcode = runcode

    # The console.
    console = InteractiveConsole(local)
    console.interact(intro, local)
Esempio n. 44
0
class ClassicPythonShell(Shell, ConsoleProgressBarMixin):
    """Classic Python shell interface.

    This class allows igraph to be embedded in Python's shell."""
    def __init__(self):
        """Constructor.

        Imports Python's classic shell"""
        Shell.__init__(self)
        ConsoleProgressBarMixin.__init__(self)
        self._shell = None

    def __call__(self):
        """Starts the embedded shell."""
        if self._shell is None:
            from code import InteractiveConsole
            self._shell = InteractiveConsole()
            print >> sys.stderr, "igraph %s running inside " % __version__,
            self._shell.runsource("from igraph import *")

        self._shell.interact()
Esempio n. 45
0
 def runcode(self, code):
     """%s""" % InteractiveConsole.runcode.__doc__
     # we need to fix-up that method as we are given a C-ext module
     # in case of cython (instead of a code-object)
     import types
     if isinstance(code, types.ModuleType):
         # slam the content of the module into our local namespace
         for k, v in code.__dict__.iteritems():
             if not k.startswith('__'):
                 self.locals[k] = v
     else:
         return InteractiveConsole.runcode(self, code)
Esempio n. 46
0
 def runsource(self,source,filename="<input>",symbol="single"):
     old_stdout = sys.stdout
     old_stderr = sys.stderr
     sys.stdout = sys.stderr = collector = MyStringIO(self)
     try:
         more = _InteractiveConsole.runsource(self,source,filename,symbol)
     finally:
         if sys.stdout is collector:
             sys.stdout = old_stdout
         if sys.stderr is collector:
             sys.stderr = old_stderr
     return more
Esempio n. 47
0
    def __init__(self, *args, **kwargs):
        InteractiveConsole.__init__(self)
        self.args = args
        self.console = Console(**kwargs)
        self.env = Environment(self.console, interactive=(len(self.args) == 1))

        commands = self.commands
        epilogue = self.epilogue

        class HelpCommand(Command):
            """ Get help.
            """

            name = "help"

            def execute(self):
                self.env.print_usage_overview(commands)
                self.env.console.write()
                self.env.console.write(epilogue)

        commands.add(HelpCommand)
Esempio n. 48
0
    def __init__(self, *args, **kwds):
        super().__init__(*args, **kwds)
        vbox = QVBoxLayout()

        prompt_area = QHBoxLayout()
        prompt_area.addWidget(QLabel("> "))
        self.input = QLineEdit()
        prompt_area.addWidget(self.input)

        self.log = QPlainTextEdit()
        vbox.addWidget(self.log)
        vbox.addLayout(prompt_area)

        self.setLayout(vbox)

        self.log.setFont(CODE_FONT)
        self.input.setFont(CODE_FONT)

        self.console = InteractiveConsole(locals=NAME_SPACE)

        self.input.returnPressed.connect(self.send_console_command)
Esempio n. 49
0
    def handle(self, conn, address):
        file_obj = conn.makefile(mode='rw')
        file_obj = gevent.backdoor._fileobject(conn, file_obj, self.stderr)

        getcurrent()._fileobj = file_obj
        getcurrent().switch_in()

        file_obj.write('Password: '******'\r\n')
        salted = password + self.salt
        hash_digest = hashlib.sha256(salted).hexdigest()

        if not hash_digest == self.hash:
            file_obj.write('\nWrong password.\n')
            conn.close()
            file_obj.close()
            return

        try:
            console = InteractiveConsole(self._create_interactive_locals())

            if sys.version_info[:3] >= (3, 6, 0):
                console.interact(banner=self.banner, exitmsg='')
            else:
                console.interact(banner=self.banner)
        except SystemExit:
            if hasattr(sys, 'exc_clear'):
                sys.exc_clear()
        finally:
            conn.close()
            file_obj.close()
Esempio n. 50
0
def interactive_client(file, address, cache_size, readonly, repair,
                       startup, storage_class=None):
    if file:
        storage = get_storage(file, storage_class=storage_class,
                readonly=readonly, repair=repair)
        description = file
    else:
        socket_address = SocketAddress.new(address)
        wait_for_server(address=socket_address)
        storage = ClientStorage(address=socket_address)
        description = socket_address
    connection = Connection(storage, cache_size=cache_size)
    console_module = ModuleType('__console__')
    sys.modules['__console__'] = console_module
    namespace = {'connection': connection,
                 'root': connection.get_root(),
                 'get': connection.get,
                 'sys': sys,
                 'os': os,
                 'int8_to_str': int8_to_str,
                 'str_to_int8': str_to_int8,
                 'pp': pprint}
    vars(console_module).update(namespace)
    configure_readline(
        vars(console_module), os.path.expanduser("~/.durushistory"))
    console = InteractiveConsole(vars(console_module))
    if startup:
        console.runsource('execfile("%s")' % os.path.expanduser(startup))
    help = ('    connection -> the Connection\n'
            '    root       -> the root instance')
    console.interact('Durus %s\n%s' % (description, help))
Esempio n. 51
0
 def handle(self, conn, address):
     f = getcurrent()._fileobj = _fileobject(conn)
     f.stderr = self.stderr
     getcurrent().switch_in()
     try:
         console = InteractiveConsole(self.locals)
         # __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__
             console.locals["__builtins__"] = __builtin__
         except ImportError:
             import builtins
             console.locals["builtins"] = builtins
         console.interact(banner=self.banner)
     except SystemExit:  # raised by quit()
         if not PY3:
             sys.exc_clear()
     finally:
         conn.close()
         f.close()
         if PYPY:
             # The underlying socket somewhere has a reference
             # that's not getting closed until finalizers run.
             # Without running them, test__backdoor.Test.test_sys_exit
             # hangs forever
             gc.collect()
Esempio n. 52
0
    def handle(self, conn, _address):  # pylint: disable=method-hidden
        """
        Interact with one remote user.

        .. versionchanged:: 1.1b2 Each connection gets its own
            ``locals`` dictionary. Previously they were shared in a
            potentially unsafe manner.
        """
        conn.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, True)  # pylint:disable=no-member
        raw_file = conn.makefile(mode="r")
        getcurrent().stdin = _StdIn(conn, raw_file)
        getcurrent().stdout = _StdErr(conn, raw_file)

        # Swizzle the inputs
        getcurrent().switch_in()
        try:
            console = InteractiveConsole(self._create_interactive_locals())
            if PY36:
                # Beginning in 3.6, the console likes to print "now exiting <class>"
                # but probably our socket is already closed, so this just causes problems.
                console.interact(banner=self.banner, exitmsg='')  # pylint:disable=unexpected-keyword-arg
            else:
                console.interact(banner=self.banner)
        except SystemExit:
            # raised by quit(); obviously this cannot propagate.
            exc_clear()  # Python 2
        finally:
            raw_file.close()
            conn.close()
Esempio n. 53
0
    def handle(self, conn, _address):  # pylint: disable=method-hidden
        """
        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())
            if sys.version_info[:3] >= (3, 6, 0):
                # Beginning in 3.6, the console likes to print "now exiting <class>"
                # but probably our socket is already closed, so this just causes problems.
                console.interact(banner=self.banner, exitmsg='')  # pylint:disable=unexpected-keyword-arg
            else:
                console.interact(banner=self.banner)
        except SystemExit:  # raised by quit()
            if hasattr(sys, 'exc_clear'):  # py2
                sys.exc_clear()
        finally:
            conn.close()
            fobj.close()
Esempio n. 54
0
        def __init__(self):
            InteractiveConsole.__init__(self)

            try:
                import readline
            except ImportError:
                pass
            else:
                import os
                import atexit

                readline.parse_and_bind('tab: complete')

                if hasattr(readline, 'read_history_file'):
                    history = os.path.expanduser('~/.sympy-history')

                    try:
                        readline.read_history_file(history)
                    except IOError:
                        pass

                    atexit.register(readline.write_history_file, history)
Esempio n. 55
0
    def __init__(self, locals=None, filename="<console>"):
        """Creates a new TrappingInteractiveConsole object."""
        InteractiveConsole.__init__(self, locals, filename)
        self._trap = OutputTrap(debug=0)
        self._stdin = []
        self._stdout = []
        self._stderr = []
        self._last_type = self._last_traceback = self._last_value = None
        #self._namespace_lock = threading.Lock()
        #self._command_lock = threading.Lock()
        self.lastCommandIndex = -1
        # I am using this user defined signal to interrupt the currently
        # running command.  I am not sure if this is the best way, but
        # it is working!
        # This doesn't work on Windows as it doesn't have this signal.
        #signal.signal(signal.SIGUSR1, self._handleSIGUSR1)

        # An exception handler.  Experimental: later we need to make the
        # modes/colors available to user configuration, etc.
        self.tbHandler = ultraTB.FormattedTB(color_scheme='NoColor',
                                             mode='Context',
                                             tb_offset=2)
Esempio n. 56
0
    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()
Esempio n. 57
0
def run_classic_shell(globals, locals, first_time=[True]):
    if first_time:
        banner = "Hit Ctrl-D to return to PuDB."
        first_time.pop()
    else:
        banner = ""

    ns = SetPropagatingDict([locals, globals], locals)

    from pudb.settings import get_save_config_path
    from os.path import join
    hist_file = join(
            get_save_config_path(),
            "shell-history")

    try:
        import readline
        import rlcompleter
        have_readline = True
    except ImportError:
        have_readline = False

    if have_readline:
        readline.set_completer(
                rlcompleter.Completer(ns).complete)
        readline.parse_and_bind("tab: complete")
        readline.clear_history()
        try:
            readline.read_history_file(hist_file)
        except OSError:
            pass

    from code import InteractiveConsole
    cons = InteractiveConsole(ns)

    cons.interact(banner)

    if have_readline:
        readline.write_history_file(hist_file)
Esempio n. 58
0
    def __init__(self, *args, **kwargs):
        InteractiveConsole.__init__(self, *args, **kwargs)

        if not readline:
            return

        try:  # this form only works with python 2.3
            self.completer = rlcompleter.Completer(self.locals)
        except:  # simpler for py2.2
            self.completer = rlcompleter.Completer()

        readline.set_completer(self.completer.complete)
        # Use tab for completions
        readline.parse_and_bind('tab: complete')
        # This forces readline to automatically print the above list when tab
        # completion is set to 'complete'.
        readline.parse_and_bind('set show-all-if-ambiguous on')
        # Bindings for incremental searches in the history. These searches
        # use the string typed so far on the command line and search
        # anything in the previous input history containing them.
        readline.parse_and_bind('"\C-r": reverse-search-history')
        readline.parse_and_bind('"\C-s": forward-search-history')