changeset 324:21584174d865

make SHOW TABLES work
author catherine@dellzilla
date Thu, 11 Feb 2010 16:07:24 -0500
parents fc1e5a141920
children 4172feeddf76
files cmd2.py docs/freefeatures.rst docs/index.rst docs/settingchanges.rst docs/unfreefeatures.rst flatten_lines.py
diffstat 6 files changed, 173 insertions(+), 112 deletions(-) [+]
line wrap: on
line diff
--- a/cmd2.py	Thu Feb 11 14:46:50 2010 -0500
+++ b/cmd2.py	Thu Feb 11 16:07:24 2010 -0500
@@ -401,7 +401,7 @@
     reserved_words = []
     feedback_to_output = False          # Do include nonessentials in >, | output
     quiet = False                       # Do not suppress nonessential output
-    debug = True
+    debug = False
     settable = stubbornDict('''
         prompt
         colors                Colorized output (*nix only)
--- a/docs/freefeatures.rst	Thu Feb 11 14:46:50 2010 -0500
+++ b/docs/freefeatures.rst	Thu Feb 11 16:07:24 2010 -0500
@@ -15,6 +15,22 @@
 Output redirection
 ==================
 
+As in a Unix shell, output of a command can be redirected:
+
+  - sent to a file with ``>``, as in ``mycommand args > filename.txt``
+  - piped (``|``) as input to operating-system commands, as in
+    ``mycommand args | wc``
+  - sent to the paste buffer, ready for the next Copy operation, by
+    ending with a bare ``>``, as in ``mycommand args >``..  Redirecting
+    to paste buffer requires software to be installed on the operating
+    system, pywin32_ on Windows or xclip_ on *nix.
+    
+.. _pywin32:: http://sourceforge.net/projects/pywin32/
+.. _xclip:: http://www.cyberciti.biz/faq/xclip-linux-insert-files-command-output-intoclipboard/
+
+  
+operating-system programs, like 
+
 Commands at start
 =================
 
--- a/docs/index.rst	Thu Feb 11 14:46:50 2010 -0500
+++ b/docs/index.rst	Thu Feb 11 16:07:24 2010 -0500
@@ -6,6 +6,21 @@
 Welcome to cmd2's documentation!
 ================================
 
+The basic use of ``cmd2`` is identical to that of cmd_.
+
+1. Create a subclass of ``cmd2.Cmd``.  Define attributes and
+   ``do_*`` methods to control its behavior.  Throughout this documentation,
+   we will assume that you are naming your subclass ``App``::
+   
+     from cmd2 import Cmd
+     class App(Cmd):
+         # customized attributes and methods here
+         
+2. Instantiate ``App`` and start the command loop::
+
+     app = App()
+     app.cmdloop()
+     
 Contents:
 
 .. toctree::
--- a/docs/settingchanges.rst	Thu Feb 11 14:46:50 2010 -0500
+++ b/docs/settingchanges.rst	Thu Feb 11 16:07:24 2010 -0500
@@ -2,11 +2,95 @@
 Features requiring only parameter changes
 =========================================
 
-Multiline commands
-==================
+Several aspects of a ``cmd2`` application's behavior
+can be controlled simply by setting attributes of ``App``.
+
+(To define your own user-settable parameters, see :ref:`parameters`
 
 Case-insensitivity
 ==================
 
+By default, all ``cmd2`` command names are case-insensitive; 
+``sing the blues`` and ``SiNg the blues`` are equivalent.  To change this, 
+set ``App.case_insensitive`` to False.
+
+Whether or not you set ``case_insensitive``, *please do not* define
+command method names with any uppercase letters.  ``cmd2`` will probably
+do something evil if you do.
+
+Multiline commands
+==================
+
+Like cmd_, ``cmd2`` assumes that a line break ends any command.
+However, ``App.multilineCommands`` is a list of commands that are assumed to span
+multiple lines.  For these commands 
+
+``cmd2.Cmd.multilineCommands`` defaults to [], so you may set your own list
+of multiline command names (without ``do_``)::
+
+    class App(Cmd):
+        multilineCommands = ['lenghtycommand']
+        def do_lengthycommand(self, args):
+            # ...
+          
+
+Shortcuts
+=========
+
+Special-character shortcuts for common commands can make life more convenient for your
+users.  Shortcuts are used without a space separating them from their arguments,
+like ``!ls``.  By default, the following shortcuts are defined:
+
+  ``?``
+    help
+    
+  ``!`` 
+    shell: run as OS-level command
+    
+  ``@``
+    load script file
+    
+  ``@@``
+    load script file; filename is relative to current script location
+    
+To define more shortcuts, update the dict ``App.shortcuts`` with the
+{'shortcut': 'command_name'} (omit ``do_``)::
+
+  class App(Cmd2):
+      Cmd2.shortcuts.update({'*': 'sneeze', '~': 'squirm'})
+
+Timing
+======
+
+Setting ``App.timing`` to ``True`` outputs timing data after
+every application command is executed.  |settable|
+
+Debug
+=====
+
+Setting ``App.debug`` to ``True`` will produce detailed error stacks
+whenever the application generates an error.  |settable|
+
+.. |settable| replace:: The user can ``set`` this parameter
+                        during application execution.  
+                        (See :ref:`parameters`)
+
+.. _quiet:
+
+Quiet
+=====
+
+Controls whether ``self.pfeedback('message')`` output is suppressed;
+useful for non-essential feedback that the user may not always want
+to read.  Only relevant if :ref:`outputters` are used.
+
+Settability
+===========
+
+If you wish the user to be able to set one of these
+application-controlling attributes while the application 
+is running, add its name to ``App.settable``.  See
+:ref:`parameters`.
+
 Abbreviated commands
 ====================
--- a/docs/unfreefeatures.rst	Thu Feb 11 14:46:50 2010 -0500
+++ b/docs/unfreefeatures.rst	Thu Feb 11 16:07:24 2010 -0500
@@ -5,13 +5,67 @@
 Command shortcuts
 =================
 
+.. _parameters:
+
 Environment parameters
 ======================
 
 Your application can define user-settable parameters 
-which your code can reference::
+which your code can reference.  Create them as class attributes
+with their default values, and add them (with optional
+documentation) to ``settable``.
+
+::
 
+    from cmd2 import Cmd
+    class App(Cmd):
+        degrees_c = 22
+        sunny = False
+        settable = Cmd.settable + '''degrees_c temperature in Celsius
+                                     sunny'''
+        def do_sunbathe(self, arg):
+            if self.degrees_c < 20:
+                result = "It's {temp} C - are you a penguin?".format(temp=self.degrees_c)
+            elif not self.sunny:
+                result = 'Too dim.'
+            else:
+                result = 'UV is bad for your skin.'
+            self.stdout.write(result + '\n')
+    app = App()
+    app.cmdloop()
+        
+::
+
+    (Cmd) set --long
+    degrees_c: 22                  # temperature in Celsius
+    sunny: False                   # 
+    (Cmd) sunbathe
+    Too dim.
+    (Cmd) set sunny yes
+    sunny - was: False
+    now: True
+    (Cmd) sunbathe
+    UV is bad for your skin.
+    (Cmd) set degrees_c 13
+    degrees_c - was: 22
+    now: 13
+    (Cmd) sunbathe
+    It's 13 C - are you a penguin?
 
 
 Commands with flags
 ===================
+
+.. _outputters:
+
+poutput, pfeedback, perror
+==========================
+
+Standard ``cmd`` applications produce their output with ``self.stdout.write('output')`` (or with ``print``,
+but ``print`` decreases output flexibility).  ``cmd2`` applications can use 
+``self.poutput('output')``, ``self.pfeedback('message')``, and ``self.perror('errmsg')``
+instead.  These methods have these advantages:
+
+  - More concise
+  - ``.pfeedback()`` destination is controlled by :ref:`quiet` parameter.
+  
\ No newline at end of file
--- a/flatten_lines.py	Thu Feb 11 14:46:50 2010 -0500
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,108 +0,0 @@
-import doctest
-
-class StubbornDict(dict):
-    '''Dictionary that tolerates many input formats.
-    Create it with stubbornDict(arg) factory function.
-    
-    >>> d = StubbornDict(large='gross', small='klein')
-    >>> sorted(d.items())
-    [('large', 'gross'), ('small', 'klein')]
-    >>> d.append(['plain', '  plaid'])
-    >>> sorted(d.items())
-    [('large', 'gross'), ('plaid', None), ('plain', None), ('small', 'klein')]
-    >>> d += '   girl Frauelein, Maedchen\\n\\n shoe schuh'
-    >>> sorted(d.items())
-    [('girl', 'Frauelein, Maedchen'), ('large', 'gross'), ('plaid', None), ('plain', None), ('shoe', 'schuh'), ('small', 'klein')]
-    '''    
-    def update(self, arg):
-        dict.update(self, StubbornDict.to_dict(arg))
-    append = update
-    def __iadd__(self, arg):
-        self.update(arg)
-        return self
-        
-    @classmethod
-    def to_dict(cls, arg):
-        'Generates dictionary from string or list of strings'
-        if hasattr(arg, 'splitlines'):
-            arg = arg.splitlines()
-        if hasattr(arg, '__getslice__'):
-            result = {}    
-            for a in arg:
-                a = a.strip()
-                if a:
-                    key_val = a.split(None, 1)
-                    key = key_val[0]
-                    if len(key_val) > 1:
-                        val = key_val[1]
-                    else:
-                        val = None
-                    result[key] = val
-        else:
-            result = arg
-        return result
-
-def stubbornDict(*arg, **kwarg):
-    '''
-    >>> sorted(stubbornDict('cow a bovine\\nhorse an equine').items())
-    [('cow', 'a bovine'), ('horse', 'an equine')]
-    >>> sorted(stubbornDict(['badger', 'porcupine a poky creature']).items())
-    [('badger', None), ('porcupine', 'a poky creature')]
-    >>> sorted(stubbornDict(turtle='has shell', frog='jumpy').items())
-    [('frog', 'jumpy'), ('turtle', 'has shell')]
-    '''
-    result = {}
-    for a in arg:
-        result.update(StubbornDict.to_dict(a))
-    result.update(kwarg)                      
-    return StubbornDict(result)
-       
-        
-class Directory(list):
-    '''A list that "wants" to consist of separate lines of text.
-    Splits multi-line strings and flattens nested lists to 
-    achieve that.
-    Also omits blank lines, strips leading/trailing whitespace.
-    
-    >>> tll = Directory(['my', 'dog\\nhas', '', [' fleas', 'and\\nticks']])
-    >>> tll
-    ['my', 'dog', 'has', 'fleas', 'and', 'ticks']
-    >>> tll.append(['and', ['spiders', 'and']])
-    >>> tll
-    ['my', 'dog', 'has', 'fleas', 'and', 'ticks', 'and', 'spiders', 'and']
-    >>> tll += 'fish'
-    >>> tll
-    ['my', 'dog', 'has', 'fleas', 'and', 'ticks', 'and', 'spiders', 'and', 'fish']
-    '''
-    def flattened(self, texts):
-        result = []
-        if isinstance(texts, basestring):
-            result.extend(texts.splitlines())
-        else:
-            for text in texts:
-                result.extend(self.flattened(text))
-        result = [r.strip() for r in result if r.strip()]
-        return result            
-    def flatten(self):
-        list.__init__(self, self.flattened(self))
-    def __init__(self, values):
-        list.__init__(self, values)
-        self.flatten()
-    def append(self, value):
-        list.append(self, value)
-        self.flatten()
-    def extend(self, values):
-        list.extend(self, values)
-        self.flatten()
-    def __setitem__(self, idx, value):
-        list.__setitem__(self, idx, value)
-        self.flatten()
-    def __iadd__(self, value):
-        if isinstance(value, basestring):
-            self.append(value)
-        else:
-            list.__iadd__(self, value)
-            self.flatten()
-        return self
-        
-doctest.testmod()
\ No newline at end of file