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._iepInterpreter.ignore_sys_exit = True # But re-enable it as soon as *this event* is processed def reEnableSysExit(): sys._iepInterpreter.ignore_sys_exit = False self._reEnableSysExitTimer = timer = QtCore.QTimer() timer.singleShot(0, reEnableSysExit)
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)
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')
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: # 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
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.storeSource(code, source) # Execute the code self.execcode(code) else: # Incomplete code self.write('Could not run code because it is incomplete.\n')
def dummy_mainloop(*args, **kwargs): printDirect(mainloopWarning)
def dummy_start(): printDirect(mainloopWarning)
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.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) 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) # Write Python banner (to stdout) NBITS = 8 * struct.calcsize("P") platform = sys.platform if platform.startswith('win'): platform = 'Windows' platform = '%s (%i bits)' % (platform, NBITS) printDirect("Python %s on %s.\n" % (sys.version.split('[')[0].rstrip(), platform)) # Integrate event loop of GUI toolkit self.guiApp = None self.guiName = guiName = startup_info['gui'].upper() guiError = '' try: if guiName in ['', 'NONE']: pass elif guiName == 'TK': self.guiApp = guiintegration.Hijacked_tk() elif guiName == 'WX': self.guiApp = guiintegration.Hijacked_wx() elif guiName == 'PYSIDE': self.guiApp = guiintegration.Hijacked_pyside() elif guiName in ['PYQT4', 'QT4']: self.guiApp = guiintegration.Hijacked_pyqt4() elif guiName == 'FLTK': self.guiApp = guiintegration.Hijacked_fltk() elif guiName == 'GTK': self.guiApp = guiintegration.Hijacked_gtk() else: guiError = 'Unkown gui: %s' % guiName except Exception: # Catch any error # Get exception info (we do it using sys.exc_info() because # we cannot catch the exception in a version independent way. type, value, tb = sys.exc_info() tb = None guiError = 'Failed to integrate event loop for %s: %s' % ( guiName, str(value)) # Write IEP part of banner (including what GUI loop is integrated) if True: iepBanner = 'This is the IEP interpreter' if guiError: iepBanner += '. ' + guiError + '\n' elif self.guiApp: iepBanner += ' with integrated event loop for ' iepBanner += guiName + '.\n' else: iepBanner += '.\n' printDirect(iepBanner) # Append project path if given projectPath = startup_info['projectPath'] if projectPath: printDirect('Prepending the project path %r to sys.path\n' % projectPath) #Actual prepending is done below, to put it before the script path # Write tips message printDirect('Type "help" for help, ' + 'type "?" for a list of *magic* commands.\n') # 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 # Init script to run on startup self._scriptToRunOnStartup = None if 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) # 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)) # Notify the running of the script printDirect('[Running script: "' + scriptFilename + '"]\n') # Run script 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('') # 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 # Run startup script (if set) filename = startup_info['startupScript'] # Should we use the default startupScript? if filename == '$PYTHONSTARTUP': filename = os.environ.get('PYTHONSTARTUP', '') # Check if it exists if filename and os.path.isfile(filename): self._scriptToRunOnStartup = filename
def dummyrun(*args, **kwargs): printDirect(mainloopWarning)
def dummy_mainloop(*args, **kw): printDirect(mainloopWarning)
def exec_(self, *args, **kwargs): printDirect(mainloopWarning)
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 '__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 IEP part of banner (including what GUI loop is integrated) if True: iepBanner = 'This is the IEP interpreter' if guiError: iepBanner += '. ' + guiError + '\n' elif guiName: iepBanner += ' with integrated event loop for ' iepBanner += guiName + '.\n' else: iepBanner += '.\n' printDirect(iepBanner) # 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 iepkernel import _nope _nope.nope()
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.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) 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) # Write Python banner (to stdout) NBITS = 8 * struct.calcsize("P") platform = sys.platform if platform.startswith('win'): platform = 'Windows' platform = '%s (%i bits)' % (platform, NBITS) printDirect("Python %s on %s.\n" % (sys.version.split('[')[0].rstrip(), platform)) # Integrate event loop of GUI toolkit self.guiApp = None self.guiName = guiName = startup_info['gui'].upper() guiError = '' try: if guiName in ['', 'NONE']: pass elif guiName == 'TK': self.guiApp = guiintegration.Hijacked_tk() elif guiName == 'WX': self.guiApp = guiintegration.Hijacked_wx() elif guiName == 'PYSIDE': self.guiApp = guiintegration.Hijacked_pyside() elif guiName in ['PYQT4', 'QT4']: self.guiApp = guiintegration.Hijacked_pyqt4() elif guiName == 'FLTK': self.guiApp = guiintegration.Hijacked_fltk() elif guiName == 'GTK': self.guiApp = guiintegration.Hijacked_gtk() else: guiError = 'Unkown gui: %s' % guiName except Exception: # Catch any error # Get exception info (we do it using sys.exc_info() because # we cannot catch the exception in a version independent way. type, value, tb = sys.exc_info() tb = None guiError = 'Failed to integrate event loop for %s: %s' % ( guiName, str(value)) # Write IEP part of banner (including what GUI loop is integrated) if True: iepBanner = 'This is the IEP interpreter' if guiError: iepBanner += '. ' + guiError + '\n' elif self.guiApp: iepBanner += ' with integrated event loop for ' iepBanner += guiName + '.\n' else: iepBanner += '.\n' printDirect(iepBanner) # Append project path if given projectPath = startup_info['projectPath'] if projectPath: printDirect('Prepending the project path %r to sys.path\n' % projectPath) #Actual prepending is done below, to put it before the script path # Write tips message printDirect('Type "help" for help, ' + 'type "?" for a list of *magic* commands.\n') # 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 # Init script to run on startup self._scriptToRunOnStartup = None if 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) # 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) ) # Notify the running of the script printDirect('[Running script: "'+scriptFilename+'"]\n') # Run script 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('') # 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 # Run startup script (if set) filename = startup_info['startupScript'] # Should we use the default startupScript? if filename == '$PYTHONSTARTUP': filename = os.environ.get('PYTHONSTARTUP','') # Check if it exists if filename and os.path.isfile(filename): self._scriptToRunOnStartup = filename