Mercurial > python-cmd2
changeset 106:2d3232693807
prompt-setting quirks
author | catherine@dellzilla |
---|---|
date | Fri, 24 Oct 2008 16:03:58 -0400 |
parents | 130340609e19 |
children | 3e2651cbe376 |
files | cmd2/cmd2.py cmd2/example.py cmd2/exampleSession.txt |
diffstat | 3 files changed, 100 insertions(+), 6 deletions(-) [+] |
line wrap: on
line diff
--- a/cmd2/cmd2.py Fri Oct 24 14:32:23 2008 -0400 +++ b/cmd2/cmd2.py Fri Oct 24 16:03:58 2008 -0400 @@ -98,7 +98,7 @@ win32clipboard.SetClipboardText(txt) win32clipboard.CloseClipboard() except ImportError: - def getPasteBuffer(): + def getPasteBuffer(*args): raise OSError, pastebufferr % ('pywin32', 'Download from http://sourceforge.net/projects/pywin32/') setPasteBuffer = getPasteBuffer else: @@ -129,9 +129,10 @@ xclipproc.stdin.write(txt) xclipproc.stdin.close() else: - def getPasteBuffer(): + def getPasteBuffer(*args): raise OSError, pastebufferr % ('xclip', 'On Debian/Ubuntu, install with "sudo apt-get install xclip"') setPasteBuffer = getPasteBuffer + writeToPasteBuffer = getPasteBuffer pyparsing.ParserElement.setDefaultWhitespaceChars(' \t') def parseSearchResults(pattern, s): @@ -151,7 +152,8 @@ multilineCommands = [] continuationPrompt = '> ' shortcuts = {'?': 'help', '!': 'shell', '@': 'load'} - excludeFromHistory = '''run r list l history hi ed edit li eof'''.split() + excludeFromHistory = '''run r list l history hi ed edit li eof'''.split() + noSpecialParse = 'set ed edit exit'.split() defaultExtension = 'txt' defaultFileName = 'command.txt' editor = os.environ.get('EDITOR') @@ -235,6 +237,14 @@ if isinstance(s, pyparsing.ParseResults): return s result = (pyparsing.SkipTo(pyparsing.StringEnd()))('fullStatement').parseString(s) + command = s.split()[0] + if self.caseInsensitive: + command = command.lower() + '''if command in self.noSpecialParse: + result['statement'] = result['upToIncluding'] = result['unterminated'] = result.fullStatement + result['command'] = command + result['args'] = ' '.join(result.fullStatement.split()[1:]) + return result''' if s[0] in self.shortcuts: s = self.shortcuts[s[0]] + ' ' + s[1:] result['statement'] = s @@ -252,7 +262,7 @@ result += parseSearchResults(self.redirectOutPattern, result.parseable) result += parseSearchResults(self.argSeparatorPattern, result.statement) if self.caseInsensitive: - result['command'] = result.command.lower() + result['command'] = result.command.lower() result['statement'] = '%s %s' % (result.command, result.args) return result @@ -433,9 +443,12 @@ paramName, val = arg.split(None, 1) paramName = self.clean(paramName) if paramName not in self.settable: - raise NotSettableError + raise NotSettableError currentVal = getattr(self, paramName) - val = cast(currentVal, self.parsed(val).unterminated) + if (val[0] == val[-1]) and val[0] in ("'", '"'): + val = val[1:-1] + else: + val = cast(currentVal, self.parsed(val).unterminated) setattr(self, paramName, val) self.stdout.write('%s - was: %s\nnow: %s\n' % (paramName, currentVal, val)) except (ValueError, AttributeError, NotSettableError), e:
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/cmd2/example.py Fri Oct 24 16:03:58 2008 -0400 @@ -0,0 +1,45 @@ +'''A sample application for cmd2.''' + +from cmd2 import Cmd, make_option, options, Cmd2TestCase +import unittest, optparse, sys + +class CmdLineApp(Cmd): + multilineCommands = ['orate'] + Cmd.shortcuts.update({'&': 'speak'}) + maxrepeats = 3 + Cmd.settable.append('maxrepeats') + + @options([make_option('-p', '--piglatin', action="store_true", help="atinLay"), + make_option('-s', '--shout', action="store_true", help="N00B EMULATION MODE"), + make_option('-r', '--repeat', type="int", help="output [n] times") + ]) + def do_speak(self, arg, opts=None): + """Repeats what you tell me to.""" + arg = ''.join(arg) + if opts.piglatin: + arg = '%s%say' % (arg[1:], arg[0]) + if opts.shout: + arg = arg.upper() + repetitions = opts.repeat or 1 + for i in range(min(repetitions, self.maxrepeats)): + self.stdout.write(arg) + self.stdout.write('\n') + # self.stdout.write is better than "print", because Cmd can be + # initialized with a non-standard output destination + + do_say = do_speak # now "say" is a synonym for "speak" + do_orate = do_speak # another synonym, but this one takes multi-line input + +class TestMyAppCase(Cmd2TestCase): + CmdApp = CmdLineApp + transcriptFileName = 'exampleSession.txt' + +parser = optparse.OptionParser() +parser.add_option('-t', '--test', dest='unittests', action='store_true', default=False, help='Run unit test suite') +(callopts, callargs) = parser.parse_args() +if callopts.unittests: + sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main() + unittest.main() +else: + app = CmdLineApp() + app.cmdloop()
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/cmd2/exampleSession.txt Fri Oct 24 16:03:58 2008 -0400 @@ -0,0 +1,36 @@ +(Cmd) say goodnight, Gracie +goodnight, Gracie +(Cmd) say -p goodnight, Gracie +oodnight, Graciegay +(Cmd) say -h +Usage: speak [options] arg + +Options: + -h, --help show this help message and exit + -p, --piglatin atinLay + -s, --shout N00B EMULATION MODE + -r REPEAT, --repeat=REPEAT + output [n] times +(Cmd) say --shout goodnight, Gracie +GOODNIGHT, GRACIE +(Cmd) set prompt 'example >>> ' +prompt - was: (Cmd) +now: example >>> +example >>> say --repeat 5 spam +spam +spam +spam +example >>> set +prompt: example >>> +editor: gedit +echo: False +maxrepeats: 3 +example >>> set maxrepeats 10 +maxrepeats - was: 3 +now: 10 +example >>> say --repeat 5 spam +spam +spam +spam +spam +spam \ No newline at end of file