Exemple #1
0
    def handle_TAB(self):
        text = "".join(self.lineBuffer).split(' ')[-1]
        if len(text) == 0:
            # Bell character
            self.terminal.write("\a")
            return

        completer = Completer(self.namespace)

        if completer.complete(text, 0):
            allMatches = list(set(completer.matches))

            # Get rid of a bunch of cruft
            builtins = __builtin__.keys()
            matches = [
                x for x in allMatches
                if x.strip('(') not in builtins and "__" not in x
            ]
            matches.sort()

            # If there are no matches, ring the terminal bell
            # If there's only one match, autocomplete it
            # If there's more than one match, print a list of matches
            if len(matches) == 0:
                self.terminal.write("\a")
                return
            elif len(matches) == 1:
                length = len(text)
                self.lineBuffer = self.lineBuffer[:-length]
                self.lineBuffer.extend(matches[0])
                self.lineBufferIndex = len(self.lineBuffer)
            else:
                # Remove text before the last dot, for brevity
                if "." in matches[0]:
                    matches = [x[x.rfind(".") + 1:] for x in matches]
                self.terminal.nextLine()
                self.terminal.write(repr(matches))
                self.terminal.nextLine()
                self.terminal.write("%s%s" % (self.ps[self.pn], ""))

            self.terminal.eraseLine()
            self.terminal.cursorBackward(self.lineBufferIndex + 5)
            self.terminal.write("%s%s" %
                                (self.ps[self.pn], "".join(self.lineBuffer)))

        else:
            self.terminal.write("\a")
Exemple #2
0
def builtins_keys():
    if isinstance(__builtins__, dict):
        return __builtins__.keys()
    return dir(__builtins__)
Exemple #3
0
 def _prepare(self):
     """ Prepare for running the main loop.
     Here we do some initialization like obtaining the startup info,
     creating the GUI application wrapper, etc.
     """
     
     # Reset debug status
     self.debugger.writestatus()
     
     # Get startup info (get a copy, or setting the new version wont trigger!)
     while self.context._stat_startup.recv() is None:
         time.sleep(0.02)
     self.startup_info = startup_info = self.context._stat_startup.recv().copy()
     
     # Set startup info (with additional info)
     if sys.platform.startswith('java'):
         import __builtin__ as builtins  # Jython
     else:
         builtins = __builtins__
     if not isinstance(builtins, dict):
         builtins = builtins.__dict__
     startup_info['builtins'] = [builtin for builtin in builtins.keys()]
     startup_info['version'] = tuple(sys.version_info)
     startup_info['keywords'] = keyword.kwlist
     self.context._stat_startup.send(startup_info)
     
     # Prepare the Python environment
     self._prepare_environment(startup_info)
     
     # Run startup code (before loading GUI toolkit or IPython
     self._run_startup_code(startup_info)
     
     # Write Python banner (to stdout)
     thename = 'Python'
     if sys.version_info[0] == 2:
         thename = 'Legacy Python'
     if '__pypy__' in sys.builtin_module_names:
         thename = 'Pypy'
     if sys.platform.startswith('java'):
         thename = 'Jython'
         # Jython cannot do struct.calcsize("P")
         import java.lang
         real_plat = java.lang.System.getProperty("os.name").lower()
         plat = '%s/%s' % (sys.platform, real_plat)
     elif sys.platform.startswith('win'):
         NBITS = 8 * struct.calcsize("P")
         plat = 'Windows (%i bits)' % NBITS
     else:
         NBITS = 8 * struct.calcsize("P")
         plat = '%s (%i bits)' % (sys.platform, NBITS) 
     printDirect("%s %s on %s.\n" %
                 (thename, sys.version.split('[')[0].rstrip(), plat))
     
     # Integrate GUI
     guiName, guiError = self._integrate_gui(startup_info)
     
     # Write pyzo part of banner (including what GUI loop is integrated)
     if True:
         pyzoBanner = 'This is the Pyzo interpreter'
     if guiError:
         pyzoBanner += '. ' + guiError + '\n'
     elif guiName:
         pyzoBanner += ' with integrated event loop for ' 
         pyzoBanner += guiName + '.\n'
     else:
         pyzoBanner += '.\n'
     printDirect(pyzoBanner)
     
     # Try loading IPython
     if startup_info.get('ipython', '').lower() in ('', 'no', 'false'):
         self._ipython = None
     else:
         try:
             self._load_ipyhon()
         except Exception:
             type, value, tb = sys.exc_info();
             del tb
             printDirect('IPython could not be loaded: %s\n' % str(value))
             self._ipython = None
     
     # Set prompts
     sys.ps1 = PS1(self)
     sys.ps2 = PS2(self)
     
     # Notify about project path
     projectPath = startup_info['projectPath']
     if projectPath:
         printDirect('Prepending the project path %r to sys.path\n' % 
             projectPath)
     
     # Write tips message.
     if self._ipython:
         import IPython
         printDirect("\nUsing IPython %s -- An enhanced Interactive Python.\n"
                     %  IPython.__version__)
         printDirect(
             "?         -> Introduction and overview of IPython's features.\n"
             "%quickref -> Quick reference.\n"
             "help      -> Python's own help system.\n"
             "object?   -> Details about 'object', "
             "use 'object??' for extra details.\n")
     else:
         printDirect("Type 'help' for help, " + 
                     "type '?' for a list of *magic* commands.\n")
     
     # Notify the running of the script
     if self._scriptToRunOnStartup:
         printDirect('\x1b[0;33mRunning script: "'+self._scriptToRunOnStartup+'"\x1b[0m\n')
     
     # Prevent app nap on OSX 9.2 and up
     # The _nope module is taken from MINRK's appnope package
     if sys.platform == "darwin" and LV(platform.mac_ver()[0]) >= LV("10.9"):
         from pyzokernel import _nope
         _nope.nope()
     
     # Setup post-mortem debugging via appropriately logged exceptions
     class PMHandler(logging.Handler):
         def emit(self, record):
             if record.exc_info:
                 sys.last_type, sys.last_value, sys.last_traceback = record.exc_info
             return record
     #
     root_logger = logging.getLogger()
     if not root_logger.handlers:
         root_logger.addHandler(logging.StreamHandler())
     root_logger.addHandler(PMHandler())
Exemple #4
0
 def _prepare(self):
     """ Prepare for running the main loop.
     Here we do some initialization like obtaining the startup info,
     creating the GUI application wrapper, etc.
     """
     
     # Reset debug status
     self.debugger.writestatus()
     
     # Get startup info (get a copy, or setting the new version wont trigger!)
     while self.context._stat_startup.recv() is None:
         time.sleep(0.02)
     self.startup_info = startup_info = self.context._stat_startup.recv().copy()
     
     # Set startup info (with additional info)
     if sys.platform.startswith('java'):
         import __builtin__ as builtins  # Jython
     else:
         builtins = __builtins__
     if not isinstance(builtins, dict):
         builtins = builtins.__dict__
     startup_info['builtins'] = [builtin for builtin in builtins.keys()]
     startup_info['version'] = tuple(sys.version_info)
     startup_info['keywords'] = keyword.kwlist
     self.context._stat_startup.send(startup_info)
     
     # Prepare the Python environment
     self._prepare_environment(startup_info)
     
     # Run startup code (before loading GUI toolkit or IPython
     self._run_startup_code(startup_info)
     
     # Write Python banner (to stdout)
     thename = 'Python'
     if sys.version_info[0] == 2:
         thename = 'Legacy Python'
     if '__pypy__' in sys.builtin_module_names:
         thename = 'Pypy'
     if sys.platform.startswith('java'):
         thename = 'Jython'
         # Jython cannot do struct.calcsize("P")
         import java.lang
         real_plat = java.lang.System.getProperty("os.name").lower()
         plat = '%s/%s' % (sys.platform, real_plat)
     elif sys.platform.startswith('win'):
         NBITS = 8 * struct.calcsize("P")
         plat = 'Windows (%i bits)' % NBITS
     else:
         NBITS = 8 * struct.calcsize("P")
         plat = '%s (%i bits)' % (sys.platform, NBITS) 
     printDirect("%s %s on %s.\n" %
                 (thename, sys.version.split('[')[0].rstrip(), plat))
     
     # Integrate GUI
     guiName, guiError = self._integrate_gui(startup_info)
     
     # Write pyzo part of banner (including what GUI loop is integrated)
     if True:
         pyzoBanner = 'This is the Pyzo interpreter'
     if guiError:
         pyzoBanner += '. ' + guiError + '\n'
     elif guiName:
         pyzoBanner += ' with integrated event loop for ' 
         pyzoBanner += guiName + '.\n'
     else:
         pyzoBanner += '.\n'
     printDirect(pyzoBanner)
     
     # Try loading IPython
     if startup_info.get('ipython', '').lower() in ('', 'no', 'false'):
         self._ipython = None
     else:
         try:
             self._load_ipyhon()
         except Exception:
             type, value, tb = sys.exc_info();
             del tb
             printDirect('IPython could not be loaded: %s\n' % str(value))
             self._ipython = None
     
     # Set prompts
     sys.ps1 = PS1(self)
     sys.ps2 = PS2(self)
     
     # Notify about project path
     projectPath = startup_info['projectPath']
     if projectPath:
         printDirect('Prepending the project path %r to sys.path\n' % 
             projectPath)
     
     # Write tips message.
     if self._ipython:
         import IPython
         printDirect("\nUsing IPython %s -- An enhanced Interactive Python.\n"
                     %  IPython.__version__)
         printDirect(
             "?         -> Introduction and overview of IPython's features.\n"
             "%quickref -> Quick reference.\n"
             "help      -> Python's own help system.\n"
             "object?   -> Details about 'object', "
             "use 'object??' for extra details.\n")
     else:
         printDirect("Type 'help' for help, " + 
                     "type '?' for a list of *magic* commands.\n")
     
     # Notify the running of the script
     if self._scriptToRunOnStartup:
         printDirect('\x1b[0;33mRunning script: "'+self._scriptToRunOnStartup+'"\x1b[0m\n')
     
     # Prevent app nap on OSX 9.2 and up
     # The _nope module is taken from MINRK's appnope package
     if sys.platform == "darwin" and LV(platform.mac_ver()[0]) >= LV("10.9"):
         from pyzokernel import _nope
         _nope.nope()
     
     # Setup post-mortem debugging via appropriately logged exceptions
     class PMHandler(logging.Handler):
         def emit(self, record):
             if record.exc_info:
                 sys.last_type, sys.last_value, sys.last_traceback = record.exc_info
             return record
     #
     root_logger = logging.getLogger()
     if not root_logger.handlers:
         root_logger.addHandler(logging.StreamHandler())
     root_logger.addHandler(PMHandler())
def builtins_keys():
    if isinstance(__builtins__, dict):
        return __builtins__.keys()
    return dir(__builtins__)