Linux/Unix > Python Essential Reference, Second Edition > A. The Python Library > Miscellaneous Modules | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105081080059255003146110

### Miscellaneous Modules

The modules in this category are used for miscellaneous tasks that don’t fit into any of the other categories.

#### `bisect`

The `bisect` module provides support for keeping lists in sorted order. It uses a bisection algorithm to do most of its work.

    bisect(list, item [, low [, high]])

Returns the index of the proper insertion point for `item` to be placed in `list` in order to maintain `list` in sorted order. `low` and `high` are indices specifying a subset of the list to be considered.

    insort(list, item [, low [, high]])

Inserts `item` into `list` in sorted order.

#### `cmd`

The `cmd` module provides a class `Cmd` that’s used as a framework for building a line-oriented command interpreter. The `Cmd` class is never instantiated directly, but is used as a base class for a class that actually implements the interpreter. An instance `c` of the `Cmd` class provides the following methods:

    c.cmdloop([intro])

Prints a banner message contained in `intro` and repeatedly issues a prompt, reads a line of input, and dispatches an appropriate action. For each line of text, the first word is stripped off and used as a command name. For a command name of `'foo'`, an attempt is made to invoke a method `do_foo()` with the remainder of the input line as a string argument. If a line contains only the character `'?'`, a predefined method `do_help()` is dispatched. If the command name is `'!'`, a method `do_shell()` is invoked (if defined). An end-of-file is converted into a string `'EOF'` and dispatched to a command `do_EOF`.

Subclasses of `Cmd` inherit a predefined method `do_help()`. When this method is invoked with an argument `'bar'`, it tries to invoke the method `help_bar()`. With no arguments, `do_help()` lists all the available help topics by listing all commands with corresponding `help_*` methods, undocumented commands (commands without corresponding `help_*` methods), and miscellaneous topics (help methods without a corresponding command). Each of the command methods should return an integer code indicating success or failure. A negative value indicates an error and causes the interpreter to return. Otherwise, the interpreter continues to read input after each command. If the `readline` module has been loaded, the command interpreter will have line editing and history capabilities.

    c.onecmd(str)

Interprets `str` as a single line of input.

    c.emptyline()

This method is called when an empty line of input is typed. It should be defined by the user. If not overridden, it repeats the last nonempty command entered.

    c.default(line)

Called when an unrecognized command is typed. By default, it prints an error message and exits.

    c.precmd()

Method executed just before the input prompt is issued. It should be overridden by derived classes.

    c.postcmd()

Method executed immediately after a command dispatch has finished.

    c.preloop()

Method executed once when `cmdloop()` is executed.

    c.postloop()

Method executed when `cmdloop()` is about to return.

The following instance variables should also be defined by a subclass of `Cmd`.

Variable | Description
--- | ---
`c` `.prompt` | Prompt printed to solicit input.
`c` `.identchars` | String of characters accepted for the command prefix.
`c` `.lastcmd` | Last nonempty command seen.
`c` `.intro` | Intro text banner; overridden using the argument to `cmdloop()`.
`c` `.doc_header` | Header to issue if the help section has a section for documented commands.
`c` `.misc_header` | Header to issue for miscellaneous help topics.
`c` `.undoc_header` | Header for undocumented commands.
`c` `.ruler` | Character used to draw separator lines under help message headers. If empty, no ruler line is drawn. The default is `'='`.

##### Example

The following example shows how this module can be used to implement an interpreter wrapper around the callable objects of a module. It also shows the interesting feature of code being executed in a class definition.

    # cmdhelp.py
    # Builds a command interpreter that allows arbitrary Python
    # commands to be typed, but reads their doc strings to create
    # a collection of help commands. Just do an execfile(cmdhelp.py)
    # in a module to utilize this.

    import cmd, sys, traceback

    # Define the interpreter class
    class Interpreter(cmd.Cmd):
          symbols = globals()
          prompt = "?>> "
          intro = "Interpreter for " + _ _name_ _

          # Find all of the callable objects and look for
          # their doc strings
           for n in symbols.keys():
                 c = symbols[n]
                 if callable(c):
                     if c._ _doc_ _:
                          exec """
    def help_%s(self):print %s._ _doc_ _
    """ % (n,n)

         # Execute an arbitrary statement
         def default(self,l):
             try:
                 exec self.lastcmd in globals()
             except:
                 traceback.print_exc()

         # Do nothing on empty line
         def emptyline(self):
             pass

         def do_EOF(self,arg):
             return -1

    # Create an instance
    interp = Interpreter()

The following code shows how this code might be used:

    Python 2.0 (#1, Feb 25 2001, 07:54:16)
    [GCC 2.95.2 19991024 (release)] on sunos5
    Type "copyright", "credits" or "license" for more information.
    >>> from socket import *
    >>> execfile("cmdhelp.py")
    >>> interp.cmdloop()
    Interpreter for _ _main_ _
    ?>> help
    Miscellaneous help topics:
    ==========================
    getservbyname     gethostbyaddr   htons           socket
    ntohs             gethostbyname   fromfd          getprotobyname
    gethostname       htonl
    Undocumented commands:
    ======================
    EOF              help
    ?>> help socket
    socket(family, type[, proto]) -> socket object
    Open a socket of the given type.  The family argument
    specifies the address family; it is normally AF_INET,
    sometimes AF_Unix.  The type argument specifies whether this
    is a stream (SOCK_STREAM) or datagram (SOCK_DGRAM) socket.
    The protocol argument defaults to 0, specifying the default
    protocol.
    ?>> s = socket(AF_INET, SOCK_STREAM)
    ?>> s.connect("www.python.org",80)
    ...

? See Also shlex (288).

#### `md5`

The `md5` module implements RSA’s MD5 message-digest algorithm. MD5 takes a sequence of input text and produces a 128-bit hash value. To compute the hash value, create an `md5` object using the `new()` function, feed data to it using the `update()` method, and then call the `digest()` method to get the hash value.

    new([arg])

Returns a new `md5` object. If `arg` is present, the method call `update(``arg` `)` is also made.

An `md5` object `m` has the following methods:

    m.update(arg)

Updates the `md5` object `m` with the string `arg` . Repeated calls are equivalent to a single call with the concatenation of all the arguments.

    m.digest()

Returns the digest of all data passed to the object using the `update()` method so far. Returns a 16-byte string that may contain nonprintable characters, including null bytes.

    m.copy()

Returns a copy of the `md5` object.

##### Example

    import md5
    m = md5.new()            # Create a new MD5 object
    m.update("Hello")
    m.update("World")
    d = m.digest()           # Get the digest

The following shortcut can also be used:

    d = md5.new("Hello World").digest()

? See Also sha (287), Internet RFC 1321.

#### `sha`

The `sha` module implements the secure hash algorithm (SHA). SHA takes a sequence of input text and produces a 160-bit hash value. To compute the hash value, create an `sha` object using the `new()` function and feed data to it.

    new([string])

Returns a new `sha` object. If `string` is present, the method call `update(``string` `)` is made.

    blocksize

Size of the blocks fed into the hash function. This is always `1`.

    digestsize

The size of the resulting digest in bytes. This is always `20`.

An instance `s` of an `sha` object has the following methods:

    s.update(arg)

Updates the `sha` object with the string `arg` . Repeated calls are equivalent to a single call with the concatenation of all the arguments.

    s.digest()

Returns the digest of all data passed to the object using the `update()` method so far. Returns a 20-byte string that may contain nonprintable characters, including null bytes.

    s.copy()

Returns a copy of the `sha` object.

    s.hexdigest()

Returns the digest value as a string of hexadecimal digits.

##### Note

- The SHA algorithm is defined by NIST document FIPS PUB 180-1: Secure Hash Standard. It’s available online at http://csrc.nist.gov/fips/fip180-1.ps.

? See Also md5 (286).

#### `shlex`

The `shlex` module provides a class `shlex` that can be used to build lexical analyzers for simple syntaxes such as shells.

    shlex([stream])

Creates an instance of the `shlex` class. `stream` specifies a file or stream-like object where characters will be read. This object must provide `read()` and `readline()` methods. If omitted, input is taken from `sys.stdin`.

An instance `s` of the `shlex` class supports the following methods:

    s.get_token()

Returns a token (as a string). If tokens have been saved with `push_token()`, a token is popped off the stack. Otherwise, the token is read from the input stream. An end-of-file returns an empty string.

    s.push_token(str)

Pushes a token onto the token stack.

In addition, the following instance variables can be set:

Variable | Description
--- | ---
`s` `.commenters` | String of characters recognized as starting a comment. Comments continue to the end of the line. Includes `'#'` by default.
`s` `.wordchars` | String of characters that form multi-character tokens. Includes all ASCII alphanumeric characters and the underscore by default.
`s` `.whitespace` | String of whitespace characters that will be skipped.
`s` `.quotes` | Characters that will be considered to be string quotes. Includes single and double quotes by default.
`s` `.lineno` | Source line number.
`s` `.token` | The token buffer.

##### Note

- Any character not declared to be a word character, whitespace, or a quote is returned as a single-character token. Also, words must be delimited by whitespace. Special symbols such as quotes and comments are not recognized within words. Thus, a word such as `isn't` is returned as a single token.

? See Also cmd (284).

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.