comparison cmd2.py @ 320:b9f19255d4b7

transcript test stuck in infinite loop?
author catherine@dellzilla
date Thu, 11 Feb 2010 14:18:28 -0500
parents c58cd7e48db7
children 7cd74e42b7f9
comparison
equal deleted inserted replaced
319:c58cd7e48db7 320:b9f19255d4b7
269 exc = self.myException 269 exc = self.myException
270 exc.loc = loc 270 exc.loc = loc
271 exc.pstr = instring 271 exc.pstr = instring
272 raise exc 272 raise exc
273 273
274 class TextLineList(list): 274 class StubbornDict(dict):
275 '''A list that "wants" to consist of separate lines of text. 275 '''Dictionary that tolerates many input formats.
276 Splits multi-line strings and flattens nested lists to 276 Create it with stubbornDict(arg) factory function.
277 achieve that. 277
278 Also omits blank lines, strips leading/trailing whitespace. 278 >>> d = StubbornDict(large='gross', small='klein')
279 279 >>> sorted(d.items())
280 >>> tll = TextLineList(['my', 'dog\\nhas', '', [' fleas', 'and\\nticks']]) 280 [('large', 'gross'), ('small', 'klein')]
281 >>> tll 281 >>> d.append(['plain', ' plaid'])
282 ['my', 'dog', 'has', 'fleas', 'and', 'ticks'] 282 >>> sorted(d.items())
283 >>> tll.append(['and', ['spiders', 'and']]) 283 [('large', 'gross'), ('plaid', None), ('plain', None), ('small', 'klein')]
284 >>> tll 284 >>> d += ' girl Frauelein, Maedchen\\n\\n shoe schuh'
285 ['my', 'dog', 'has', 'fleas', 'and', 'ticks', 'and', 'spiders', 'and'] 285 >>> sorted(d.items())
286 >>> tll += 'fish' 286 [('girl', 'Frauelein, Maedchen'), ('large', 'gross'), ('plaid', None), ('plain', None), ('shoe', 'schuh'), ('small', 'klein')]
287 >>> tll 287 '''
288 ['my', 'dog', 'has', 'fleas', 'and', 'ticks', 'and', 'spiders', 'and', 'fish'] 288 def update(self, arg):
289 dict.update(self, StubbornDict.to_dict(arg))
290 append = update
291 def __iadd__(self, arg):
292 self.update(arg)
293 return self
294
295 @classmethod
296 def to_dict(cls, arg):
297 'Generates dictionary from string or list of strings'
298 if hasattr(arg, 'splitlines'):
299 arg = arg.splitlines()
300 if hasattr(arg, '__getslice__'):
301 result = {}
302 for a in arg:
303 a = a.strip()
304 if a:
305 key_val = a.split(None, 1)
306 key = key_val[0]
307 if len(key_val) > 1:
308 val = key_val[1]
309 else:
310 val = ''
311 result[key] = val
312 else:
313 result = arg
314 return result
315
316 def stubbornDict(*arg, **kwarg):
289 ''' 317 '''
290 def flattened(self, texts): 318 >>> sorted(stubbornDict('cow a bovine\\nhorse an equine').items())
291 result = [] 319 [('cow', 'a bovine'), ('horse', 'an equine')]
292 if isinstance(texts, basestring): 320 >>> sorted(stubbornDict(['badger', 'porcupine a poky creature']).items())
293 result.extend(texts.splitlines()) 321 [('badger', None), ('porcupine', 'a poky creature')]
294 else: 322 >>> sorted(stubbornDict(turtle='has shell', frog='jumpy').items())
295 for text in texts: 323 [('frog', 'jumpy'), ('turtle', 'has shell')]
296 result.extend(self.flattened(text)) 324 '''
297 result = [r.strip() for r in result if r.strip()] 325 result = {}
298 return result 326 for a in arg:
299 def flatten(self): 327 result.update(StubbornDict.to_dict(a))
300 list.__init__(self, self.flattened(self)) 328 result.update(kwarg)
301 def __init__(self, values): 329 return StubbornDict(result)
302 list.__init__(self, values)
303 self.flatten()
304 def append(self, value):
305 list.append(self, value)
306 self.flatten()
307 def extend(self, values):
308 list.extend(self, values)
309 self.flatten()
310 def __setitem__(self, idx, value):
311 list.__setitem__(self, idx, value)
312 self.flatten()
313 def __iadd__(self, value):
314 if isinstance(value, basestring):
315 self.append(value)
316 else:
317 list.__iadd__(self, value)
318 self.flatten()
319 return self
320 330
321 def replace_with_file_contents(fname): 331 def replace_with_file_contents(fname):
322 if fname: 332 if fname:
323 try: 333 try:
324 result = open(os.path.expanduser(fname[0])).read() 334 result = open(os.path.expanduser(fname[0])).read()
381 current_script_dir = None 391 current_script_dir = None
382 reserved_words = [] 392 reserved_words = []
383 feedback_to_output = False # Do include nonessentials in >, | output 393 feedback_to_output = False # Do include nonessentials in >, | output
384 quiet = False # Do not suppress nonessential output 394 quiet = False # Do not suppress nonessential output
385 debug = True 395 debug = True
386 settable = TextLineList(''' 396 settable = stubbornDict('''
387 prompt 397 prompt
388 colors Colorized output (*nix only) 398 colors Colorized output (*nix only)
389 continuation_prompt 399 continuation_prompt
390 debug 400 debug
391 default_file_name for `save`, `load`, etc. 401 default_file_name for `save`, `load`, etc.
470 self._init_parser() 480 self._init_parser()
471 self.pystate = {} 481 self.pystate = {}
472 self.shortcuts = sorted(self.shortcuts.items(), reverse=True) 482 self.shortcuts = sorted(self.shortcuts.items(), reverse=True)
473 self.keywords = self.reserved_words + [fname[3:] for fname in dir(self) 483 self.keywords = self.reserved_words + [fname[3:] for fname in dir(self)
474 if fname.startswith('do_')] 484 if fname.startswith('do_')]
475 import pdb; pdb.set_trace()
476 def linelist(arg): 485 def linelist(arg):
477 result = [] 486 result = []
478 487
479 self.settable = (l.strip() for l in self.settable if l.strip())
480 self.settable = dict(ljust(l.split(None,1), 2, '') for l in self.settable)
481 self.doubleDashComment = pyparsing.NotAny(pyparsing.Or(options_defined)) + pyparsing.Literal('--') + pyparsing.restOfLine 488 self.doubleDashComment = pyparsing.NotAny(pyparsing.Or(options_defined)) + pyparsing.Literal('--') + pyparsing.restOfLine
482 489
483 def do_shortcuts(self, args): 490 def do_shortcuts(self, args):
484 """Lists single-key shortcuts available.""" 491 """Lists single-key shortcuts available."""
485 result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts)) 492 result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts))