Exemplo n.º 1
0
 def runfile(self, fname):
     """  To execute the startup script. """ 
     
     # Get text (make sure it ends with a newline)
     try:
         source = open(fname, 'rb').read().decode('UTF-8')
     except Exception:
         printDirect('Could not read script (decoding using UTF-8): "' + fname + '"\n')
         return
     try:
         source = source.replace('\r\n', '\n').replace('\r','\n')
         if source[-1] != '\n':
             source += '\n'
     except Exception:        
         printDirect('Could not execute script: "' + fname + '"\n')
         return
     
     # Try compiling the source
     code = None
     try:            
         # Compile
         code = self.compilecode(source, fname, "exec")
     except (OverflowError, SyntaxError, ValueError):
         time.sleep(0.2) # Give stdout time to be send
         self.showsyntaxerror(fname)
         return
     
     if code:
         # Store the source using the (id of the) code object as a key
         self._codeCollection.store_source(code, source)
         # Execute the code
         self.execcode(code)
     else:
         # Incomplete code
         self.write('Could not run code because it is incomplete.\n')
Exemplo n.º 2
0
            def exec_(self, *args, **kwargs):
                """ This function does nothing, except printing a
                warning message. The point is that a Qt App can crash
                quite hard if an object goes out of scope, and the error
                is not obvious.
                """
                printDirect(mainloopWarning_qt + '\n')

                # Store local namespaces (scopes) of any functions that
                # precede this call. It might have a widget or application
                # object that should not be deleted ...
                import inspect, __main__
                for caller in inspect.stack()[1:]:
                    frame, name = caller[0], caller[3]
                    if name.startswith('<'):  # most probably "<module>"
                        break
                    else:
                        __main__.__dict__[name + '_locals'] = frame.f_locals

                # Tell interpreter to ignore any system exits
                sys._pyzoInterpreter.ignore_sys_exit = True

                # But re-enable it as soon as *this event* is processed
                def reEnableSysExit():
                    sys._pyzoInterpreter.ignore_sys_exit = False

                self._reEnableSysExitTimer = timer = QtCore.QTimer()
                timer.singleShot(0, reEnableSysExit)
Exemplo n.º 3
0
 def exec_(self, *args, **kwargs):
     """ This function does nothing, except printing a
     warning message. The point is that a Qt App can crash
     quite hard if an object goes out of scope, and the error
     is not obvious.
     """
     printDirect(mainloopWarning_qt+'\n')
     
     # Store local namespaces (scopes) of any functions that
     # precede this call. It might have a widget or application
     # object that should not be deleted ...
     import inspect, __main__
     for caller in inspect.stack()[1:]:
         frame, name = caller[0], caller[3]
         if name.startswith('<'):  # most probably "<module>"
             break
         else:
             __main__.__dict__[name+'_locals'] = frame.f_locals
     
     # Tell interpreter to ignore any system exits
     sys._pyzoInterpreter.ignore_sys_exit = True
     
     # But re-enable it as soon as *this event* is processed
     def reEnableSysExit():
         sys._pyzoInterpreter.ignore_sys_exit = False
     self._reEnableSysExitTimer = timer = QtCore.QTimer()
     timer.singleShot(0, reEnableSysExit)
Exemplo n.º 4
0
 def runfile(self, fname):
     """  To execute the startup script. """ 
     
     # Get text (make sure it ends with a newline)
     try:
         source = open(fname, 'rb').read().decode('UTF-8')
     except Exception:
         printDirect('Could not read script (decoding using UTF-8): "' + fname + '"\n')
         return
     try:
         source = source.replace('\r\n', '\n').replace('\r','\n')
         if source[-1] != '\n':
             source += '\n'
     except Exception:        
         printDirect('Could not execute script: "' + fname + '"\n')
         return
     
     # Try compiling the source
     code = None
     try:            
         # Compile
         code = self.compilecode(source, fname, "exec")
     except (OverflowError, SyntaxError, ValueError):
         time.sleep(0.2) # Give stdout time to be send
         self.showsyntaxerror(fname)
         return
     
     if code:
         # Store the source using the (id of the) code object as a key
         self._codeCollection.store_source(code, source)
         # Execute the code
         self.execcode(code)
     else:
         # Incomplete code
         self.write('Could not run code because it is incomplete.\n')
Exemplo n.º 5
0
    def _prepare_environment(self, startup_info):
        """Prepare the Python environment. There are two possibilities:
        either we run a script or we run interactively.
        """

        # Get whether we should (and can) run as script
        scriptFilename = startup_info["scriptFile"]
        if scriptFilename:
            if not os.path.isfile(scriptFilename):
                printDirect('Invalid script file: "' + scriptFilename + '"\n')
                scriptFilename = None

        # Get project path
        projectPath = startup_info["projectPath"]

        if scriptFilename.endswith(".ipynb"):
            # Run Jupyter notebook
            import notebook.notebookapp

            sys.argv = ["jupyter_notebook", scriptFilename]
            sys.exit(notebook.notebookapp.main())

        elif scriptFilename:
            # RUN AS SCRIPT
            # Set __file__  (note that __name__ is already '__main__')
            self.locals["__file__"] = scriptFilename
            # Set command line arguments
            sys.argv[:] = []
            sys.argv.append(scriptFilename)
            sys.argv.extend(shlex.split(startup_info.get("argv", "")))
            # Insert script directory to path
            theDir = os.path.abspath(os.path.dirname(scriptFilename))
            if theDir not in sys.path:
                sys.path.insert(0, theDir)
            if projectPath is not None:
                sys.path.insert(0, projectPath)
            # Go to script dir
            os.chdir(os.path.dirname(scriptFilename))
            # Run script later
            self._scriptToRunOnStartup = scriptFilename
        else:
            # RUN INTERACTIVELY
            # No __file__ (note that __name__ is already '__main__')
            self.locals.pop("__file__", "")
            # Remove all command line arguments, set first to empty string
            sys.argv[:] = []
            sys.argv.append("")
            sys.argv.extend(shlex.split(startup_info.get("argv", "")))
            # Insert current directory to path
            sys.path.insert(0, "")
            if projectPath:
                sys.path.insert(0, projectPath)
            # Go to start dir
            startDir = startup_info["startDir"]
            if startDir and os.path.isdir(startDir):
                os.chdir(startDir)
            else:
                os.chdir(os.path.expanduser("~"))  # home dir
Exemplo n.º 6
0
 def _prepare_environment(self, startup_info):
     """ Prepare the Python environment. There are two possibilities:
     either we run a script or we run interactively.
     """
     
     # Get whether we should (and can) run as script
     scriptFilename = startup_info['scriptFile']
     if scriptFilename:
         if not os.path.isfile(scriptFilename):
             printDirect('Invalid script file: "'+scriptFilename+'"\n')
             scriptFilename = None
     
     # Get project path
     projectPath = startup_info['projectPath']
     
     if scriptFilename.endswith('.ipynb'):
         # Run Jupyter notebook
         import notebook.notebookapp
         sys.argv = ['jupyter_notebook', scriptFilename]
         sys.exit(notebook.notebookapp.main())
     
     elif scriptFilename:
         # RUN AS SCRIPT
         # Set __file__  (note that __name__ is already '__main__')
         self.locals['__file__'] = scriptFilename
         # Set command line arguments
         sys.argv[:] = []
         sys.argv.append(scriptFilename)
         sys.argv.extend(shlex.split(startup_info.get('argv', '')))
         # Insert script directory to path
         theDir = os.path.abspath( os.path.dirname(scriptFilename) )
         if theDir not in sys.path:
             sys.path.insert(0, theDir)
         if projectPath is not None:
             sys.path.insert(0,projectPath)
         # Go to script dir
         os.chdir( os.path.dirname(scriptFilename) )
         # Run script later
         self._scriptToRunOnStartup = scriptFilename
     else:
         # RUN INTERACTIVELY
         # No __file__ (note that __name__ is already '__main__')
         self.locals.pop('__file__','')
         # Remove all command line arguments, set first to empty string
         sys.argv[:] = []
         sys.argv.append('')
         sys.argv.extend(shlex.split(startup_info.get('argv', '')))
         # Insert current directory to path
         sys.path.insert(0, '')
         if projectPath:
             sys.path.insert(0,projectPath)
         # Go to start dir
         startDir = startup_info['startDir']
         if startDir and os.path.isdir(startDir):
             os.chdir(startDir)
         else:
             os.chdir(os.path.expanduser('~')) # home dir 
Exemplo n.º 7
0
    def runfile(self, fname):
        """  To execute the startup script. """

        # Get text (make sure it ends with a newline)
        try:
            bb = open(fname, 'rb').read()
            encoding = 'UTF-8'
            firstline = bb.split('\n'.encode(), 1)[0].decode('ascii', 'ignore')
            if firstline.startswith('#') and 'coding' in firstline:
                encoding = firstline.split('coding',
                                           1)[-1].strip(' \t\r\n:=-*')
            source = bb.decode(encoding)
        except Exception:
            printDirect('Could not read script (decoding using %s): %r\n' %
                        (encoding, fname))
            return
        try:
            source = source.replace('\r\n', '\n').replace('\r', '\n')
            if source[-1] != '\n':
                source += '\n'
        except Exception:
            printDirect('Could not execute script: "' + fname + '"\n')
            return

        # Try compiling the source
        code = None
        try:
            # Compile
            code = self.compilecode(source, fname, "exec")
        except (OverflowError, SyntaxError, ValueError):
            time.sleep(0.2)  # Give stdout time to be send
            self.showsyntaxerror(fname)
            return

        if code:
            # Store the source using the (id of the) code object as a key
            self._codeCollection.store_source(code, source)
            # Execute the code
            self.execcode(code)
        else:
            # Incomplete code
            self.write('Could not run code because it is incomplete.\n')
Exemplo n.º 8
0
 def runfile(self, fname):
     """  To execute the startup script. """
     
     # Get text (make sure it ends with a newline)
     try:
         bb = open(fname, 'rb').read()
         encoding = 'UTF-8'
         firstline = bb.split('\n'.encode(), 1)[0].decode('ascii', 'ignore')
         if firstline.startswith('#') and 'coding' in firstline:
             encoding = firstline.split('coding', 1)[-1].strip(' \t\r\n:=-*')
         source = bb.decode(encoding)
     except Exception:
         printDirect('Could not read script (decoding using %s): %r\n' % (encoding, fname))
         return
     try:
         source = source.replace('\r\n', '\n').replace('\r','\n')
         if source[-1] != '\n':
             source += '\n'
     except Exception:
         printDirect('Could not execute script: "' + fname + '"\n')
         return
     
     # Try compiling the source
     code = None
     try:
         # Compile
         code = self.compilecode(source, fname, "exec")
     except (OverflowError, SyntaxError, ValueError):
         time.sleep(0.2) # Give stdout time to be send
         self.showsyntaxerror(fname)
         return
     
     if code:
         # Store the source using the (id of the) code object as a key
         self._codeCollection.store_source(code, source)
         # Execute the code
         self.execcode(code)
     else:
         # Incomplete code
         self.write('Could not run code because it is incomplete.\n')
Exemplo n.º 9
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())
Exemplo n.º 10
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())
Exemplo n.º 11
0
def print_mainloop_warning(msg=None):
    global _printed_warning
    if not _printed_warning:
        _printed_warning = True
        msg = msg or mainloopWarning
        printDirect(msg)
Exemplo n.º 12
0
 def dummy_mainloop(*args, **kwargs):
     printDirect(mainloopWarning)
Exemplo n.º 13
0
 def dummy_start():
     printDirect(mainloopWarning)
Exemplo n.º 14
0
 def dummy_mainloop(*args, **kwargs):
     printDirect(mainloopWarning)        
Exemplo n.º 15
0
 def dummy_start():
     printDirect(mainloopWarning)
     sys._pyzoInterpreter.ignore_sys_exit = True
     self.app.add_callback(reset_sys_exit)
Exemplo n.º 16
0
 def dummy_start():
     printDirect(mainloopWarning)
     sys._pyzoInterpreter.ignore_sys_exit = True
     self.app.add_callback(reset_sys_exit)
Exemplo n.º 17
0
 def dummy_start():
     printDirect(mainloopWarning)