def pdoc(self, obj, oname='', formatter=None): """Print the docstring for any object. Optional: -formatter: a function to run the docstring through for specially formatted docstrings.""" head = self.__head # so that itpl can find it even if private if formatter is None: ds = inspect.getdoc(obj) else: ds = formatter(inspect.getdoc(obj)) if type(obj) is types.ClassType: init_ds = inspect.getdoc(obj.__init__) output = itpl('$head("Class Docstring:")\n' '$indent(ds)\n' '$head("Constructor Docstring"):\n' '$indent(init_ds)') elif type(obj) is types.InstanceType and hasattr(obj, '__call__'): call_ds = inspect.getdoc(obj.__call__) if call_ds: output = itpl('$head("Class Docstring:")\n$indent(ds)\n' '$head("Calling Docstring:")\n$indent(call_ds)') else: output = ds else: output = ds if output == None: self.noinfo('documentation', oname) return page(output)
def __call__(self,lst,pos='',**kw): """Prints the nested list numbering levels.""" kw.setdefault('indent',' ') kw.setdefault('sep',': ') kw.setdefault('start',0) kw.setdefault('stop',len(lst)) # we need to remove start and stop from kw so they don't propagate # into a recursive call for a nested list. start = kw['start']; del kw['start'] stop = kw['stop']; del kw['stop'] if self.depth == 0 and 'header' in kw.keys(): print kw['header'] for idx in range(start,stop): elem = lst[idx] if type(elem)==type([]): self.depth += 1 self.__call__(elem,itpl('$pos$idx,'),**kw) self.depth -= 1 else: printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
def gen_url(radius, zipcode, make): return urllib.urlopen(itpl(BASE_URL))
def __init__(self, name, usage=None, rc=Struct(opts=None, args=None), user_ns=None): # Put a reference to self in builtins so that any form of embedded or # imported code can test for being inside IPython. __builtin__.__dict__['__IPYTHON__'] = self # Keep in the builtins a flag for when IPython is active. We set it # with setdefault so that multiple nested IPythons don't clobber one # another. Each will increase its value by one upon being activated, # which also gives us a way to determine the nesting level. __builtin__.__dict__.setdefault('__IPYTHON__active', 0) # Create the namespace where the user will operate: # FIXME. For some strange reason, __builtins__ is showing up at user # level as a dict instead of a module. This is a manual fix, but I # should really track down where the problem is coming from. Alex # Schmolck reported this problem first. if user_ns is None: self.user_ns = { '__name__': '__IPYTHON__main__', name: self, '__builtins__': __builtin__, } else: self.user_ns = user_ns # We need to insert into sys.modules something that looks like a # module but which accesses the IPython namespace, for shelve and # pickle to work interatctively. Normally they rely on getting # everything out of __main__, but for embedding purposes each IPython # instance has its own private namespace, so we can't go shoving # everything into __main__. try: main_name = self.user_ns['__name__'] except KeyError: raise KeyError, 'user_ns dictionary MUST have a "__name__" key' else: sys.modules[main_name] = _FakeModule(self.user_ns) # List of input with multi-line handling. # Fill its zero entry, user counter starts at 1 self.input_hist = InputList(['\n']) # list of visited directories self.dir_hist = [os.getcwd()] # dict of output history self.output_hist = {} # make global variables for user access to these self.user_ns['_ih'] = self.input_hist self.user_ns['_oh'] = self.output_hist self.user_ns['_dh'] = self.dir_hist # user aliases to input and output histories self.user_ns['In'] = self.user_ns['_ih'] self.user_ns['Out'] = self.user_ns['_oh'] # class initializations code.InteractiveConsole.__init__(self, locals=self.user_ns) Logger.__init__(self, log_ns=self.user_ns) Magic.__init__(self) # an ugly hack to get a pointer to the shell, so I can start writing magic # code via this pointer instead of the current mixin salad. Magic.set_shell(self, self) # hooks is a Struct holding pointers to various system hooks, and will # be used for further user-side customizations in the future #self.hooks = Struct(ps1 = sys.ps1,ps2 = sys.ps2,display = sys.displayhook) self.hooks = Struct() self.name = name self.usage_min = """\ An enhanced console for Python. Features are: - Readline support if present - Completion in the local namespace, eg. type TAB twice at the prompt. - Logging of input, see command-line options. - Systemshell escape by the ! , eg !ls - Magic commands, starting with a @ (like @ls, @pwd, @cd, etc.) - Keeps track of locally defined variables @who, @whos - Show object information with a ? eg ?x or x? (use ?? for more info). """ if usage: self.usage = usage else: self.usage = self.usage_min # Storage self.rc = rc # This will hold all configuration information self.inputcache = [] self._boundcache = [] self.pager = 'less' # temporary files used for various purposes. Deleted at exit. self.tempfiles = [] # for pushd/popd management try: self.home_dir = get_home_dir() except HomeDirError: if os.name == 'dos': # final, desperate hack for Win9x self.home_dir = os.path.join('C:', 'Program Files', 'IPython') else: print 'Unsupported operating system:', os.name print 'Exiting...' sys.exit() self.dir_stack = [os.getcwd().replace(self.home_dir, '~')] # escapes for automatic behavior on the command line self.ESC_SHELL = '!' self.ESC_HELP = '?' self.ESC_MAGIC = '@' self.ESC_QUOTE = ',' self.ESC_PAREN = '/' # RegExp for splitting line contents into pre-char//first word-method//rest # update the regexp if the above escapes are changed self.line_split = re.compile( r'(^[\s*!\?@,/]?)([\?\w\.]+\w*\s*)(\(?.*$)') # RegExp to identify potential function names self.fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) ?$') # try to catch also methods for stuff in lists/tuples/dicts: # off (experimental). For this to work, the line_split regexp would # need to be modified so it wouldn't break things at '['. That line # is nasty enough that I shouldn't change it until I can test it _well_. #self.fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') # keep track of where we started running (mainly for crash post-mortem) self.starting_dir = os.getcwd() # Attributes for Logger mixin class, make defaults here self._dolog = 0 self.LOG = '' self.LOGDEF = '.InteractiveShell.log' self.LOGMODE = 'over' self.LOGHEAD = Itpl( """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE *** #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW #log# opts = $self.rc.opts #log# args = $self.rc.args #log# It is safe to make manual edits below here. #log#----------------------------------------------------------------------- """) # Various switches which can be set self.CACHELENGTH = 5000 # this is cheap, it's just text self.BANNER = itpl("Python $sys.version on $sys.platform\n" "$sys.copyright\nIPP\nType ? for more help\n") # TraceBack handlers: # Need two, one for syntax errors and one for other exceptions. # plain/color self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor') # This one is initialized with an offset, meaning we always want to # remove the topmost item in the traceback, which is our own internal # code. Valid modes: plain/color/verbose self.InteractiveTB = ultraTB.AutoFormattedTB(mode='Plain', color_scheme='NoColor', tb_offset=1) # Object inspector ins_colors = OInspect.InspectColors code_colors = PyColorize.ANSICodeColors self.inspector = OInspect.Inspector(ins_colors, code_colors, 'NoColor') # List of shell commands to auto-define if os.name == 'posix': auto_shell = { 'ls': 'ls -F', 'mkdir': 'mkdir', 'rmdir': 'rmdir', 'mv': 'mv', 'rm': 'rm -i', 'rmf': 'rm -f', 'less': 'less', 'cat': 'cat', 'clear': 'clear', 'lc': 'ls -F -o --color' } elif os.name == 'nt': auto_shell = { 'dir': 'dir /on', 'ls': 'dir /on', 'ddir': 'dir /ad /on', 'ld': 'dir /ad /on', 'mkdir': 'mkdir', 'rmdir': 'rmdir', 'ren': 'ren', 'cls': 'cls', 'more': 'type', 'type': 'type' } else: auto_shell = {} for name, cmd in auto_shell.items(): self.magic_alias(name + ' ' + cmd)
def __call__(self, etype, evalue, etb): # Report tracebacks shouldn't use color in general (safer for users) color_scheme = 'NoColor' # Use this ONLY for developer debugging (keep commented out for release) #color_scheme = 'Linux' try: rptdir = self.IP.rc.ipythondir except: rptdir = os.getcwd() if not os.path.isdir(rptdir): rptdir = os.getcwd() self.report_name = os.path.join(rptdir, 'IPython_crash_report.txt') self.TBhandler = ultraTB.VerboseTB(color_scheme=color_scheme, long_header=1) traceback = self.TBhandler.text(etype, evalue, etb, context=31) # print traceback to screen print >> sys.stderr, traceback # and generate a complete report on disk try: report = open(self.report_name, 'w') except: print >> sys.stderr, 'Could not create crash report on disk.' return msg = itpl('\n' + '*' * 70 + '\n' """ Oops, IPython crashed. We do our best to make it stable, but... A crash report was automatically generated with the following information: - A verbatim copy of the traceback above this text. - A copy of your input history during this session. - Data on your current IPython configuration. It was left in the file named: \t'$self.report_name' If you can email this file to the developers, the information in it will help them in understanding and correcting the problem. You can mail it to $self.bug_contact at $self.mailto with the subject 'IPython Crash Report'. If you want to do it now, the following command will work (under Unix): mail -s 'IPython Crash Report' $self.mailto < $self.report_name """) print >> sys.stderr, msg sec_sep = '\n\n' + '*' * 75 + '\n\n' report.write('*' * 75 + '\n\n' + 'IPython post-mortem report\n\n') report.write('IPython version: ' + __version__) report.write(sec_sep + 'Current user configuration structure:\n\n') report.write(pformat(self.IP.rc.dict())) report.write(sec_sep + 'Crash traceback:\n\n' + traceback) try: report.write(sec_sep + "History of session input:") for line in self.IP.user_ns['_ih']: report.write(line) report.write( '\n*** Last line of input (may not be in above history):\n') report.write(self.IP._last_input_line + '\n') except: pass report.close()