def debug(frame=None, frames_back=1): if IPython.__version__ >= '0.11': from IPython.core.debugger import Pdb try: ip = get_ipython() except NameError: from IPython.frontend.terminal.embed \ import InteractiveShellEmbed ip = InteractiveShellEmbed() colors = ip.colors else: from IPython.Debugger import Pdb from IPython.Shell import IPShell from IPython import ipapi ip = ipapi.get() if ip is None: IPShell(argv=['']) ip = ipapi.get() colors = ip.options.colors sys.excepthook = old_excepthook if frame is None: frame = sys._getframe(frames_back) Pdb(colors).set_trace(frame)
def get_def_colors(): # Inspirated in https://github.com/gotcha/ipdb/blob/master/ipdb/__main__.py def_colors = 'Linux' import IPython if IPython.__version__ > '0.10.2': from IPython.core.debugger import Pdb try: get_ipython except NameError: from IPython.frontend.terminal.embed import InteractiveShellEmbed ipshell = InteractiveShellEmbed() def_colors = ipshell.colors else: try: def_colors = get_ipython.im_self.colors except AttributeError: def_colors = get_ipython.__self__.colors else: from IPython.Debugger import Pdb from IPython.Shell import IPShell from IPython import ipapi ip = ipapi.get() if ip is None: IPShell(argv=['']) ip = ipapi.get() def_colors = ip.options.colors return def_colors
def showtraceback(self, IP, type, value, tb): """Display the exception that just occurred. We remove the first stack item because it is our own code. Strip out references to modules within pyraf unless reprint or debug is set. """ import linecache, traceback, sys, os import IPython.ultraTB # get the color scheme from the user configuration file and pass # it to the trace formatter csm = 'Linux' # default if ipapi: ip = ipapi.get() # this works in vers prior to 1.* csm = ip.options['colors'] linecache.checkcache() tblist = traceback.extract_tb(tb) tbskip = 0 for tb1 in tblist: path, filename = os.path.split(tb1[0]) path = os.path.normpath(os.path.join(os.getcwd(), path)) if path[:len(self.pyrafDir)] == self.pyrafDir or \ path[:len(self.ipythonDir)] == self.ipythonDir or \ filename == "<ipython console>": tbskip += 1 color_tb = IPython.ultraTB.AutoFormattedTB( mode=self.traceback_mode, tb_offset=tbskip, color_scheme=csm) color_tb(type, value, tb)
def __init__(self,argv=None,user_ns=None,user_global_ns=None, cin=None, cout=None,cerr=None, input_func=None): """ """ if input_func: IPython.iplib.raw_input_original = input_func if cin: IPython.Shell.Term.cin = cin if cout: IPython.Shell.Term.cout = cout if cerr: IPython.Shell.Term.cerr = cerr if argv is None: argv=[] IPython.iplib.raw_input = lambda x: None self.term = IPython.genutils.IOTerm(cin=cin, cout=cout, cerr=cerr) os.environ['TERM'] = 'dumb' excepthook = sys.excepthook self.IP = IPython.Shell.make_IPython(argv, user_ns=user_ns, user_global_ns=user_global_ns, embedded=True, shell_class=IPython.Shell.InteractiveShell) self.IP.system = lambda cmd: self.shell(self.IP.var_expand(cmd), header='IPython system call: ', verbose=self.IP.rc.system_verbose) # Get a hold of the public IPython API object and use it self.ip = ipapi.get() self.ip.magic('colors LightBG') sys.excepthook = excepthook self.iter_more = 0 self.complete_sep = re.compile('[\s\{\}\[\]\(\)]')
def main(): global zope_debug ip = ipapi.get() o = ip.options # autocall to "full" mode (smart mode is default, I like full mode) SOFTWARE_HOME = os.environ.get( "SOFTWARE_HOME" ) sys.path.append( SOFTWARE_HOME ) print "SOFTWARE_HOME=%s\n" % SOFTWARE_HOME zope_debug = ZopeDebug() # <HACK ALERT> import pdb; pdb.set_trace = ipy_set_trace # </HACK ALERT> # I like my banner minimal. o.banner = "ZOPE Py %s IPy %s\n" % (sys.version.split('\n')[0],Release.version) print textwrap.dedent("""\ ZOPE mode iPython shell. Bound names: app portal utils.{ %s } Uses the $SOFTWARE_HOME and $CONFIG_FILE environment variables. """ % ( ",".join([ x for x in dir(zope_debug.utils) if not x.startswith("_") ] ) ) ) ip.user_ns.update( zope_debug.namespace )
def optionLoad(self): try: ip = get() path = ip.IP.rc.ipythondir opt = open(path + '/options.conf','r') lines = opt.readlines() opt.close() options_ipython_panel = self.ipython_panel.getOptions() options_history_panel = self.history_panel.getOptions() for line in lines: key = line.split('=')[0] value = line.split('=')[1].replace('\n','').replace('\r','') if key in options_ipython_panel.keys(): options_ipython_panel[key]['value'] = value elif key in options_history_panel.keys(): options_history_panel[key]['value'] = value else: print >>sys.__stdout__,"Warning: key ",key,"not found in widget options. Check Options.conf" self.ipython_panel.reloadOptions(options_ipython_panel) self.history_panel.reloadOptions(options_history_panel) except IOError: print >>sys.__stdout__,"Could not open Options.conf, defaulting to default values."
def _findsource_ipython(self,f): from IPython import ipapi self.ip = ipapi.get() buf = self.ip.IP.input_hist_raw[-1].splitlines()[1:] wsource = [l+'\n' for l in buf ] return strip_whitespace(wsource)
def importMainOrIPythonMain(): try: from IPython import ipapi mainDict = ipapi.get().user_ns except: mainDict = __import__('__main__').__dict__ return mainDict
def __init__(self, colors=None): """Create a local debugger instance. :Parameters: - `colors` (None): a string containing the name of the color scheme to use, it must be one of IPython's valid color schemes. If not given, the function will default to the current IPython scheme when running inside IPython, and to 'NoColor' otherwise. Usage example: from IPython.Debugger import Tracer; debug_here = Tracer() ... later in your code debug_here() # -> will open up the debugger at that point. Once the debugger activates, you can use all of its regular commands to step through code, set breakpoints, etc. See the pdb documentation from the Python standard library for usage details. """ global __IPYTHON__ try: __IPYTHON__ except NameError: # Outside of ipython, we set our own exception hook manually __IPYTHON__ = ipapi.get(True, False) BdbQuit_excepthook.excepthook_ori = sys.excepthook sys.excepthook = BdbQuit_excepthook def_colors = "NoColor" try: # Limited tab completion support import rlcompleter, readline readline.parse_and_bind("tab: complete") except ImportError: pass else: # In ipython, we use its custom exception handler mechanism ip = ipapi.get() def_colors = ip.options.colors ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook) if colors is None: colors = def_colors self.debugger = Pdb(colors)
def __str__(self): ip = ipapi.get() for cmd in reversed(ip.IP.input_hist_raw): parts = cmd.strip().split() if len(parts) < 2 or parts[-1] in ['$LA', 'LA()']: continue return parts[-1] return ""
def post_mortem(tb): ip = ipapi.get() def_colors = ip.options.colors p = Pdb(def_colors) p.reset() while tb.tb_next is not None: tb = tb.tb_next p.interaction(tb.tb_frame, tb)
def main(): import ipy_user_conf ip = ipapi.get() o = ip.options o.pylab_import_all = 0 ip.ex("from hyperspy.hspy import *") ip.ex("__version__ = Release.version") o.banner = Release.info
def get_ipython(): """Get the global InteractiveShell instance. Returns None if no InteractiveShell instance is registered. """ if is_it_running_from_ipython is False: return None import IPython ipy_version = LooseVersion(IPython.__version__) if ipy_version < LooseVersion("0.11"): from IPython import ipapi ip = ipapi.get() elif ipy_version < LooseVersion("1.0"): from IPython.core import ipapi ip = ipapi.get() else: ip = IPython.get_ipython() return ip
def debug(self, err): ec, ev, tb = err stdout = sys.stdout sys.stdout = sys.__stdout__ try: ip = ipapi.get() p = ipdb.Pdb(ip.options.colors) p.reset() p.interaction(None, tb) finally: sys.stdout = stdout
def __init__(self, clemulate=1, cmddict={}, cmdchars=("a-zA-Z_.","0-9")): import re, sys, os self.reword = re.compile('[a-z]*') self._cl_emulation = clemulate self.cmddict = cmddict self.recmd = re.compile( "[ \t]*(?P<cmd>" + "[" + cmdchars[0] + "][" + cmdchars[0] + cmdchars[1] + "]*" + ")[ \t]*") self.locals = _locals import pyraf self.pyrafDir = os.path.dirname(pyraf.__file__) import IPython self.ipythonDir = os.path.dirname(IPython.__file__) self.traceback_mode = "Context" if VERY_OLD_IPY: self._ipython_api = ipapi.get() self._ipython_magic = self._ipython_api.IP.lsmagic() # skip % self._ipython_api.expose_magic( "set_pyraf_magic", self.set_pyraf_magic) self._ipython_api.expose_magic( "use_pyraf_traceback", self.use_pyraf_traceback) self._ipython_api.expose_magic( "use_pyraf_cl_emulation", self.use_pyraf_cl_emulation) self._ipython_api.expose_magic( "use_pyraf_readline_completer", self.use_pyraf_completer) self._pyraf_completer = IPythonIrafCompleter(self._ipython_api.IP) # Replace IPython prefilter with self.prefilter bound method. def foo_filter(*args): return self.prefilter(*args) self.InteractiveShell.prefilter = foo_filter else: self._ipython_api = pyraf._ipyshell # this is pretty far into IPython, i.e. very breakable # lsmagic() returns a dict of 2 dicts: 'cell', and 'line' if hasattr(self._ipython_api, 'magics_manager'): self._ipython_magic = self._ipython_api.magics_manager.lsmagic()['line'].keys() else: print('Please upgrade your version of IPython.') pfmgr = self._ipython_api.prefilter_manager self.priority = 0 # transformer needs this, low val = done first self.enabled = True # a transformer needs this pfmgr.register_transformer(self)
def set_trace(): try: import nose.core from traceback import extract_stack nose_core_path = nose.core.__file__.rstrip('c') if nose_core_path in (entry[0] for entry in extract_stack()): from IPython.Shell import Term Term.cout = sys.stdout = sys.__stdout__ except ImportError: pass ip = ipapi.get() def_colors = ip.options.colors Pdb(def_colors).set_trace(sys._getframe().f_back)
def optionSave(self, name, value): ip = get() path = ip.IP.rc.ipythondir opt = open(path + '/options.conf','w') try: options_ipython_panel = self.ipython_panel.getOptions() options_history_panel = self.history_panel.getOptions() for key in options_ipython_panel.keys(): opt.write(key + '=' + options_ipython_panel[key]['value']+'\n') for key in options_history_panel.keys(): opt.write(key + '=' + options_history_panel[key]['value']+'\n') finally: opt.close()
def main(): ip = ipapi.get() # PyMVPA specific ip.ex('import mvpa') # and now the whole suite # but no, since ipython segfaults (tested with version 0.8.4) # the whole things seems to be related to RPy and friends # running the same command after IPython startup is completed # is no problem, though. #ip.ex('from mvpa.suite import *') print """ ########################### # Welcome to PyMVPA %s # ########################### """ % mvpa.__version__
def enable_ipython_completer(): import sys if 'IPython' in sys.modules: ip_running = False try: from IPython.core.interactiveshell import InteractiveShell ip_running = InteractiveShell.initialized() except ImportError: # support <ipython-0.11 from IPython import ipapi as _ipapi ip_running = _ipapi.get() is not None except Exception: pass if ip_running: from . import ipy_completer return ipy_completer.load_ipython_extension() raise RuntimeError('completer must be enabled in active ipython session')
def _formatTracebackLines(lnum, index, lines, Colors, lvals=None,scheme=None): numbers_width = INDENT_SIZE - 1 res = [] i = lnum - index # This lets us get fully syntax-highlighted tracebacks. if scheme is None: ipinst = ipapi.get() if ipinst is not None: scheme = ipinst.IP.rc.colors else: scheme = DEFAULT_SCHEME _line_format = _parser.format2 for line in lines: new_line, err = _line_format(line,'str',scheme) if not err: line = new_line if i == lnum: # This is the line with the error pad = numbers_width - len(str(i)) if pad >= 3: marker = '-'*(pad-3) + '-> ' elif pad == 2: marker = '> ' elif pad == 1: marker = '>' else: marker = '' num = marker + str(i) line = '%s%s%s %s%s' %(Colors.linenoEm, num, Colors.line, line, Colors.Normal) else: num = '%*s' % (numbers_width,i) line = '%s%s%s %s' %(Colors.lineno, num, Colors.Normal, line) res.append(line) if lvals and i == lnum: res.append(lvals + '\n') i = i + 1 return res
def set_trace(): """Set debug break. Use ipdb insetead of pdb when possible. Because appengine changes stdin/out/err descriptors, using plain pdb won't work. We need to restore some of the default settings before using it. """ # remap stadradr descriptors, because gae is stupid for attr in ('stdin', 'stdout'): setattr(sys, attr, getattr(sys, '__%s__' % attr)) try: from IPython.Debugger import Pdb from IPython import ipapi ip = ipapi.get() def_colors = ip.options.colors return Pdb(def_colors).set_trace(sys._getframe().f_back) except ImportError: # fallback to pdb from pdb import Pdb return Pdb().set_trace(sys._getframe().f_back)
def eexecfile (file): """Execute FILE and then remove it. Execute the file within the __main__ namespace. If we get an exception, print a traceback with the top frame (ourselves) excluded.""" # We cannot use real execfile since it has a bug where the file stays # locked forever (under w32) if SyntaxError occurs. # --- code based on code.py and PyShell.py. try: try: try: from IPython import ipapi ip = ipapi.get() ip.runlines(open(file).readlines()) except: execfile(file, globals(), __main__.__dict__) except (OverflowError, SyntaxError, ValueError): # FIXME: When can compile() raise anything else than # SyntaxError ???? format_exception (file, False) return finally: os.remove (file)
def main(): ip = ipapi.get() o = ip.options # Set the prompts similar to the defaults o.prompt_in1 = '>>> ' o.prompt_in2 = '... ' o.prompt_out = '' # Add a blank line before each new set of inputs. This is needed by # doctest to distinguish each test from the next. o.separate_in = '\n' o.separate_out = '' o.separate_out2 = '' # Disable pprint, so that outputs are printed as similarly to standard # python as possible o.pprint = False # Use plain exceptions, to also resemble normal pyhton. o.xmode = 'plain' # Store the activity flag in the metadata bag from the running shell ip.IP.meta.doctest_mode = True
def findsource_ipython(f, name): from IPython import ipapi ip = ipapi.get() wsource = [l + '\n' for l in ip.IP.input_hist_raw[-1].splitlines()[1:]] return strip_whitespace(wsource, name, 4)
def findsource_ipython(f, name): from IPython import ipapi ip = ipapi.get() wsource = [l+'\n' for l in ip.IP.input_hist_raw[-1].splitlines()[1:]] return strip_whitespace(wsource, name, 4)
def pdb_builder(): return Pdb(ipapi.get().options.colors)
def main(): ip = ipapi.get() o = ip.options # autocall to "full" mode (smart mode is default, I like full mode) o.autocall = 2 # Jason Orendorff's path class is handy to have in user namespace # if you are doing shell-like stuff try: ip.ex("from path import path") except ImportError: pass # beefed up %env is handy in shell mode import envpersist ip.ex('import os') ip.ex("def up(): os.chdir('..')") # Get pysh-like prompt for all profiles. o.prompt_in1 = '\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> ' o.prompt_in2 = '\C_Green|\C_LightGreen\D\C_Green> ' o.prompt_out = '<\#> ' from IPython import Release import sys # I like my banner minimal. o.banner = "Py %s IPy %s\n" % (sys.version.split('\n')[0], Release.version) # make 'd' an alias for ls -F ip.magic('alias d ls -F --color=auto') # Make available all system commands through "rehashing" immediately. # You can comment these lines out to speed up startup on very slow # machines, and to conserve a bit of memory. Note that pysh profile does this # automatically ip.IP.default_option('cd', '-q') o.prompts_pad_left = "1" # Remove all blank lines in between prompts, like a normal shell. o.separate_in = "0" o.separate_out = "0" o.separate_out2 = "0" # now alias all syscommands db = ip.db syscmds = db.get("syscmdlist", []) if not syscmds: print textwrap.dedent(""" System command list not initialized, probably the first run... running %rehashx to refresh the command list. Run %rehashx again to refresh command list (after installing new software etc.) """) ip.magic('rehashx') syscmds = db.get("syscmdlist") for cmd in syscmds: #print "al",cmd noext, ext = os.path.splitext(cmd) ip.IP.alias_table[noext] = (0, cmd) extend_shell_behavior(ip)
print ' ___ _ _' print ' / _ \ | | (_)' print '/ /_\ \___| |_ _ _ __' print '| _ / __| __| | \'__)' print '| | | \__ \ |_| | |' print '\_| |_/___/\__|_|_|' print '' print 'This file is part of FIREwire' print 'FIREwire Copyright (C) 2008 - 2010 Julien Bert' print 'This program comes with ABSOLUTELY NO WARRANTY; for details type "licence".' print 'This is free software, and you are welcome to redistribute it' print 'under certain conditions; type "licence" for details.' print 'GNU General Public License version 3' print '' #print '** Astir Shell V1.00 **\n' ipshell = IPShellEmbed(banner="** Astir Shell V1.00 **") ipapi.get().set_hook("generate_prompt", myinputprompt) ipapi.get().set_hook("generate_output_prompt", myoutputprompt) ipshell()
def set_trace(): ip = ipapi.get() def_colors = ip.options.colors Pdb(def_colors).set_trace(sys._getframe().f_back)
def main(): ip = ipapi.get() o = ip.options # autocall to "full" mode (smart mode is default, I like full mode) o.autocall = 2 # Jason Orendorff's path class is handy to have in user namespace # if you are doing shell-like stuff try: ip.ex("from IPython.external.path import path") except ImportError: pass # beefed up %env is handy in shell mode import envpersist # To see where mycmd resides (in path/aliases), do %which mycmd import ipy_which # tab completers for hg, svn, ... import ipy_app_completers # To make executables foo and bar in mybin usable without PATH change, do: # %rehashdir c:/mybin # %store foo # %store bar import ipy_rehashdir # does not work without subprocess module! #import ipy_signals ip.ex('import os') ip.ex("def up(): os.chdir('..')") ip.user_ns['LA'] = LastArgFinder() # Nice prompt o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#> ' o.prompt_in2 = r'\C_Green|\C_LightGreen\D\C_Green> ' o.prompt_out = '<\#> ' from IPython import Release import sys # Non-chatty banner o.banner = "IPython %s [on Py %s]\n" % (Release.version, sys.version.split(None, 1)[0]) ip.IP.default_option('cd', '-q') ip.IP.default_option('macro', '-r') # If you only rarely want to execute the things you %edit... #ip.IP.default_option('edit','-x') o.prompts_pad_left = "1" # Remove all blank lines in between prompts, like a normal shell. o.separate_in = "0" o.separate_out = "0" o.separate_out2 = "0" # now alias all syscommands db = ip.db syscmds = db.get("syscmdlist", []) if not syscmds: print textwrap.dedent(""" System command list not initialized, probably the first run... running %rehashx to refresh the command list. Run %rehashx again to refresh command list (after installing new software etc.) """) ip.magic('rehashx') syscmds = db.get("syscmdlist") # lowcase aliases on win32 only if os.name == 'posix': mapper = lambda s: s else: def mapper(s): return s.lower() for cmd in syscmds: # print "sys",cmd #dbg noext, ext = os.path.splitext(cmd) key = mapper(noext) if key not in ip.IP.alias_table: ip.defalias(key, cmd) # mglob combines 'find', recursion, exclusion... '%mglob?' to learn more ip.load("IPython.external.mglob") # win32 is crippled w/o cygwin, try to help it a little bit if sys.platform == 'win32': if 'cygwin' in os.environ['PATH'].lower(): # use the colors of cygwin ls (recommended) ip.defalias('d', 'ls -F --color=auto') else: # get icp, imv, imkdir, igrep, irm,... ip.load('ipy_fsops') # and the next best thing to real 'ls -F' ip.defalias('d', 'dir /w /og /on') ip.set_hook('input_prefilter', dotslash_prefilter_f) extend_shell_behavior(ip)
# This module was contributed by Mario Pastorelli <*****@*****.**> # It is released in the public domain # This tool provides "j" for ipython # To use it, copy it in your ~/.ipython directory # and add the following line to ipy_user_conf.py: # import autojump_ipython import os import subprocess as sub from IPython.ipapi import get from IPython.iplib import InteractiveShell ip = get() def magic_j(self,parameter_s=''): cmd = ['autojump']+parameter_s.split() # print 'executing autojump with args %s' % str(cmd) newpath=sub.Popen(cmd,stdout=sub.PIPE,shell=False).communicate()[0][:-1] # delete last '\n' # print 'Autojump answer: \'%s\'' % newpath if newpath: ip.magic('cd \'%s\'' % newpath) def cd_decorator(f): def autojump_cd_monitor(self,parameter_s=''): f(self,parameter_s) sub.call(['autojump','-a',os.getcwd()]) return autojump_cd_monitor # Add the new magic function to the class dict and decorate magic_cd: InteractiveShell.magic_j = magic_j
c = SocketConnection('localhost') db = c.modules.pydebug.pydebug_instance except AttributeError: print('cannot connect to localhost') except Exception,e: print(str(e)) assert False #define interface with the command line ipython instance #definitions for ipython 0.11 #from IPython.core import ipapi #definition for ipython 0.10 from IPython import ipapi ip = ipapi.get() global __IPYTHON__ try: __IPYTHON__ print('IPTHON is defined') except: __IPYTHON__ = ip def edit_glue(self,filename,linenumber=0): _logger.debug('position to editor file:%s. Line:%d'%(filename,linenumber)) if filename.find('<console') > -1: _logger.debug('rejected positioning to console') return if filename.endswith('.pyc') or filename.endswith('.pyo'): filename = filename[:-1] if linenumber > 0:
def __call__(self, hist_idx=None): ip = ipapi.get() if hist_idx is None: return str(self) return ip.IP.input_hist_raw[hist_idx].strip().split()[-1]
import sys import os import IPython.ipapi as ipapi ip = ipapi.get() if ip is None: ip = ipapi.get(allow_dummy=True, dummy_warn=False) from ipymake.ipymruntimecore import * IPYM_ORIGINAL_FILE_HASH = "992ff940a7bad2ff4e571822e787d6e10878140d" IPYM_ORIGINAL_FILE_NAME = """alice.py""" IPYM_COMMAND_ARGS = "" import sys import os ip.runlines(""" IPYM_INSTALL_PREFIX = '~/tmp' IPYM_BINARY_PREFIX = '/bin' IPYM_LIBRARY_PREFIX = '/lib'
def main(): ip = ipapi.get() o = ip.options # autocall to "full" mode (smart mode is default, I like full mode) o.autocall = 2 # Jason Orendorff's path class is handy to have in user namespace # if you are doing shell-like stuff try: ip.ex("from path import path") except ImportError: pass # beefed up %env is handy in shell mode import envpersist import ipy_which import ipy_stock_completers ip.ex('import os') ip.ex("def up(): os.chdir('..')") # Nice prompt o.prompt_in1 = r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#> ' o.prompt_in2 = r'\C_Green|\C_LightGreen\D\C_Green> ' o.prompt_out = '<\#> ' from IPython import Release import sys # I like my banner minimal. o.banner = "Py %s IPy %s\n" % (sys.version.split('\n')[0], Release.version) # make 'd' an alias for ls -F ip.magic('alias d ls -F --color=auto') ip.IP.default_option('cd', '-q') # If you only rarely want to execute the things you %edit... #ip.IP.default_option('edit','-x') o.prompts_pad_left = "1" # Remove all blank lines in between prompts, like a normal shell. o.separate_in = "0" o.separate_out = "0" o.separate_out2 = "0" # now alias all syscommands db = ip.db syscmds = db.get("syscmdlist", []) if not syscmds: print textwrap.dedent(""" System command list not initialized, probably the first run... running %rehashx to refresh the command list. Run %rehashx again to refresh command list (after installing new software etc.) """) ip.magic('rehashx') syscmds = db.get("syscmdlist") for cmd in syscmds: #print "al",cmd noext, ext = os.path.splitext(cmd) ip.IP.alias_table[noext] = (0, cmd) extend_shell_behavior(ip)
# Deprecated way to handle special types # These are going away in 1.4 from h5t import py_new_vlen as new_vlen from h5t import py_get_vlen as get_vlen from h5t import py_new_enum as new_enum from h5t import py_get_enum as get_enum __doc__ = __doc__ % (version.version, version.hdf5_version, version.api_version) __all__ = [ 'h5', 'h5f', 'h5g', 'h5s', 'h5t', 'h5d', 'h5a', 'h5p', 'h5r', 'h5o', 'h5l', 'h5z', 'h5i', 'version', 'File', 'Group', 'Dataset', 'Datatype', 'AttributeManager', 'H5Error', 'get_config', 'is_hdf5', 'special_dtype', 'check_dtype', 'SoftLink', 'ExternalLink' ] try: try: from IPython.core.iplib import InteractiveShell ip_running = InteractiveShell.initialized() except ImportError: # support <ipython-0.11 from IPython import ipapi ip_running = ipapi.get() is not None if ip_running: import _ipy_completer _ipy_completer.activate() except Exception: pass
from IPython.utils import io if 'nose' in sys.modules.keys(): def update_stdout(): # setup stdout to ensure output is available with nose io.stdout = sys.stdout = sys.__stdout__ else: def update_stdout(): pass else: from IPython.Debugger import Pdb, BdbQuit_excepthook from IPython.Shell import IPShell from IPython import ipapi ip = ipapi.get() if ip is None: IPShell(argv=['']) ip = ipapi.get() def_colors = ip.options.colors def_exec_lines = [] from IPython.Shell import Term if 'nose' in sys.modules.keys(): def update_stdout(): # setup stdout to ensure output is available with nose Term.cout = sys.stdout = sys.__stdout__ else: def update_stdout(): pass
def _format_exception_only(self, etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.exc_info()[:2]. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list. Also lifted nearly verbatim from traceback.py """ have_filedata = False Colors = self.Colors list = [] try: stype = Colors.excName + etype.__name__ + Colors.Normal except AttributeError: stype = etype # String exceptions don't get special coloring if value is None: list.append( str(stype) + '\n') else: if etype is SyntaxError: try: msg, (filename, lineno, offset, line) = value except: have_filedata = False else: have_filedata = True #print 'filename is',filename # dbg if not filename: filename = "<string>" list.append('%s File %s"%s"%s, line %s%d%s\n' % \ (Colors.normalEm, Colors.filenameEm, filename, Colors.normalEm, Colors.linenoEm, lineno, Colors.Normal )) if line is not None: i = 0 while i < len(line) and line[i].isspace(): i = i+1 list.append('%s %s%s\n' % (Colors.line, line.strip(), Colors.Normal)) if offset is not None: s = ' ' for c in line[i:offset-1]: if c.isspace(): s = s + c else: s = s + ' ' list.append('%s%s^%s\n' % (Colors.caret, s, Colors.Normal) ) value = msg s = self._some_str(value) if s: list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, Colors.Normal, s)) else: list.append('%s\n' % str(stype)) # vds:>> if have_filedata: ipinst = ipapi.get() if ipinst is not None: ipinst.IP.hooks.synchronize_with_editor(filename, lineno, 0) # vds:<< return list