PowerConsole Core modules and classes

pwc

PowerConsole utilizes namespace package pwc to put all modules used by various command and extensions packages that are distributed separately into single cohesive system.

So command and extension developers are encouraged to place all modules into it. To do that, simply create a pwc directory in your project and place __init__.py file in it with next content:

__import__('pkg_resources').declare_namespace(__name__)

pwc.base

Data

pwc.base.displays
Global cache of display instances. Dictionary where key is context of the display.
pwc.base.renderers
Global cache of object renderer classes.

Exceptions

exception pwc.base.pcException(message)

An exception generated directly by PowerConsole.

All exceptions thrown by PowerConsole should be derived from this class.

exception pwc.base.pcError(message)
General programming error generated by PowerConsole.
exception pwc.base.pcParseError(message)
Wrongly specified internal command.

Functions

pwc.base.isiterable(obj)
Returns True if ‘obj’ supports new iteration protocol.
pwc.base.unquote(str)
Returns ‘str’ unquoted.
pwc.base.iif(expr, valueA, valueB)
pwc.base.asString(expr)
pwc.base.columnize(array, displaywidth=80, colsep=' ', arrange_vertical=True, ljust=True, lineprefix='')

“Generator func that returns a list of strings as a compact set of columns arranged horizontally or vertically.

For example, for a line width of 4 characters (arranged vertically):

[‘1’, ‘2,’, ‘3’, ‘4’] => ‘1 3’,‘2 4’

or arranged horizontally:

[‘1’, ‘2,’, ‘3’, ‘4’] => ‘1 2’ ‘3 4’

Each column is only as wide as necessary. By default, columns are separated by two spaces - one was not legible enough. Set “colsep” to adjust the string separate columns. Set `displaywidth’ to set the line width.

Normally, consecutive items go down from the top to bottom from the left-most column to the right-most. If “arrange_vertical” is set false, consecutive items will go across, left to right, top to bottom.

Author:Rocky Bernstein, http://code.google.com/p/pycolumnize/

Adapted to generator function by Pavel Cisar

Classes

Helper classes

class pwc.base.struct
Class to hold arbitrary data as attributes (structure).
class pwc.base.LateBindingProperty
Recipe from Tim Delaney, 2005/03/31
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/408713
class C(object):

    def getx(self):
        print 'C.getx'
        return self._x

    def setx(self, x):
        print 'C.setx'
        self._x = x

    def delx(self):
        print 'C.delx'
        del self._x

    x = LateBindingProperty(getx, setx, delx)

class D(C):

    def setx(self, x):
        print 'D.setx'
        super(D, self).setx(x)

    def delx(self):
        print 'D.delx'
        super(D, self).delx()

c = C()
c.x = 1
c.x
c.x
del c.x

print

d = D()
d.x = 1
d.x
d.x
del d.x

This has the advantages that:

  1. You get back an actual property object (with attendant memory savings, performance increases, etc);
  2. It’s the same syntax as using property(fget, fset, fdel, doc) except for the name;
  3. It will fail earlier (when you define the class as opposed to when you use it).
  4. It’s shorter ;)
  5. If you inspect the property you will get back functions with the correct __name__, __doc__, etc.

Command

class pwc.base.Command(controller)

Base class for all PowerConsole built-in commands.

__init__(controller)
_compile(s, l, tokens)

pyparsing parse action that converts parsed command.

Command is converted into string with python code to call it’s implementation function with parameters.

The resulting code has format: _NAME_execute(PARAM_LIST)

where:

Name:is value of grammar token with ResultsName CMD_NAME
Param_list:is comma-separated list of named parameters (i.e. name=value) constructed from named grammar tokens.

Because the result must be valid Python function call, parameter values are quoted using next logic:

  1. IntType is converted to arg=value
  2. String types are converted to arg=’value’ using correct quotation for given value.
  3. Value of any other type is converted to arg=’value’
Important:This parse action must be assigned to root (and only to root) token in defined grammar.

EXAMPLE:

Let's have next grammar: action [argument]

So the definition in descendant's __init__ is:
    self.keyAction = CaselessKeyword('action')
    self.cmdAction = self.keyAction.setResultsName(CMD_NAME) +                     Optional(self.arg.setResultsName('arg'))
    self.cmdAction.setParseAction(self._compile)

Then next commands will be translated into:
>>>parseString('action')
_action_execute()
>>>parseString('action 1')
_action_execute(arg=1)
>>>parseString('action doIt')
_action_execute(arg='doIt')
>>>parseString("action 'doIt'")
_action_execute(arg="'doIt'")
>>>parseString('action "doIt"')
_action_execute(arg='"doIt"')
>>>parseString('''action "It's smile time!"''')
_action_execute(arg=It's smile time!)
>>>parseString('action obj')
_action_execute(arg='obj')
_makeNameNode(node)
Helper functions that sets the specified PyParsing grammar node as command identification node.
_tokenToInt(st, loc, toks)
Helper PyParsing parse action that convers parsed token to integer.
_getContextLocals(depth=0)

Return locals from specified frame.

‘depth’ is number of frames up in stack; 0 means one frame above caller.

_getUserNamespace()
Return dictionary of names defined as locals in controller.
_fail(s, loc, expr, err)

pyparsing fail action that raises ParseFatalException.

It’s used to stop parsing with error on required grammar elements.

EXAMPLE: Next defined grammar element for USER ‘username’ will fail when ‘username’ is not specified:

optUser = keyUser +                 QuotedString("'").setResultsName('user').setFailAction(self._fail)
_getGrammar()

Return grammar for command.

Descendant has to override it.

_getCmdKeyword()

Return grammar element for command’s keyword(s).

It’s used by interpreter to identify input lines where internal command starts whithout fully parsing the command.

Descendant has to override it.

execute(**kwargs)

Main method that implements the command.

Defined grammar (GRAMMAR_FULL) must convert the command text into python code to call this function under name ‘_<cmdname>_execute’ with specified arguments.

Descendant has to override it.

getGrammar(grammarType)

Returns grammar definition of requested type.

Return None if grammar of requested type is not available.

There could be multiple ‘types’ of grammar for single command used for different purposes.

Now recognized grammar types are:

Grammar_full:Grammar used to parse and convert command to callable.
Grammar_chkcmd:Grammar for check whether line might be this command.
getName()

Returns the command name.

By default, the name is lowercased class name without ‘cmd’ prefix (if it’s present).

ARG
Grammar node for command argument. It may consist of several lines.
CHUNK
Grammar node for arbitrary text up to the line separator
EXPR
Grammar node for expression. It may consist of several lines.
FILENAME
Grammar node for file name
IDENT
Grammar node for identificator
INTEGER
Grammar node for INTEGER value
PATH
Grammar node for path

User Interface Provider

class pwc.base.UserInterfaceProvider(packages, factory=None)

Base class for PowerConsole user interface providers.

Default implementation returns default displays and input dialogs.

All methods returning UI instances take optional ‘context’ parameter that define use context for requested UI widget. It’s typically a command name optionally followed by internal context specification(s) separated by dot, for example: ‘show.detail’, ‘show.list’ etc. If context is not specified, then ‘main’ context is assumed.

The rationale behind it is to allow UI customization for various contexts via configuration.

getDisplay(context='main', interface=1)

Returns a Display instance.

Interface:One or more interface specifications for requested display.
Context:String that defines usage context for requested display. See class docstring for details. Defaults to ‘main’.
raw_input(prompt='')

Write a prompt and read a line.

The returned line does not include the trailing newline. When the user enters the EOF key sequence, EOFError is raised.

The base implementation uses the built-in function raw_input(); a subclass may replace this with a different implementation.

Display

class pwc.base.Display

Default Display.

Supports all defined display interfaces.

provides()
Returns list of interface codes this display implements.
visitDefaultAction(obj)
Prints string representation of ‘obj’ to the stdout.
write(text='')
Writes text (without the line end).
writeLine(line='')
Writes line of text (with the line end).
writeLines(lines)
Writes lines from iterable (with the line end after each line)
writeList(items)

Writes list of items in columnized format.

Items:List or iterable of elements. If item is not a string, then its str() representation is used.
writeObject(obj)

Prints string representation of object to the stdout.

Uses Visitor pattern to write out the object. If object doesn’t supports Visitors, then it attempts to use custom renderers that can handle the object, otherwise str() representation is written.

writeObjectList(items)

Display list of objects.

Uses Visitor pattern to write out the object. If object doesn’t supports Visitors, then str() representation is written.

writeTable(description, data)

Prints data from iterable in tabular format according to layout specification.

Description:List of tuples that describe the table layout. (COLUMN_NAME,WIDTH)
Data:Iterable. Each yield must return list or tuple of items.
class pwc.base.ObjectVisitor

Base/mixin class for object visitors.

__getattr__(name)

Dispatch unhandled visitor call.

When visitXXX is called by visitee but it’s not defined by visitor, it first makes a lookup in list of externally defined visitor extensions and eventually returns visitDefaultAction if no specialised method is found.

handleObject(obj)

Handle objects that don’t support the visitor pattern.

Makes a lookup in list of externally defined visitor extensions for the first one that can handle object of this type. Calls visitDefaultAction if no specialised handler is found.

visitDefaultAction(obj)
Default visitor action. Does nothing in base implementation.

Help Provider

pwc.base.HELP_PREFIX

Name prefix for attributes/methods that define content for help topics.

HELP_PREFIX = ‘help_’

class pwc.base.HelpProvider(pythonhelp)

Base class for all PowerConsole built-in help topic providers.

By default, it provides all attributes which name starts with HELP_PREFIX as help topics (without HELP_PREFIX). These attributes are typically strings to be printed, but could be also callables that return the help text.

For special help handling subclasses could rewrite getTopics, CanHandle and getHelp methods.

canHandle(topic)

Return True if this instance can provide help for ‘topic’.

By default, instance can provide help if it has attribute with name matching HELP_PREFIX+topic pattern.

getHelp(topic)

Return help for ‘topic’.

By default, it returns attribute with name matching HELP_PREFIX+topic.

getTopics()

Return list of topics handled by provider.

It’s possible that provider can handle additional topics not included in this list, but all listed topics must be handled.

By default, it returns list of names for instance attributes with name matching HELP_PREFIX+topic pattern stripped from HELP_PREFIX.

Extension Package

class pwc.base.ExtensionPackage(pkgname)

Base class for PowerConsole extension packages.

Uses setuptools resources to load attribute values from package metadata. See PowerConsole Extension Specification for more information about PowerConsole Extension packages.

name
Unique name of the extension package.
version
String containing package version.
summary
Short package description.
url
URL to package home website.
download_url
URL to package download area.
description
Package description.
author
Name of package author.
author_email
Author’s contact e-mail address.
license
License used for package distrbution.

pwc.interpreter

Execution engine

class pwc.interpreter.Interpreter(packages=[], locals=None, ui_provider=None, ui_factory=None)

Interpreter based on code.InteractiveInterpreter from Python Library.

Attributes:

Packages:List of package interface objects.
Ui_provider:UserInterfaceProvider instance used by interpreter.
Locals:the dictionary in which code will be executed.
Compile:CommandCompiler instance.
Linecont:Line continuation marker.
Terminator:Default terminator string for terminated commands
Commands:Disctionary of installed commands, key is command name.
Full_grammar:Complete grammar for internal commands.
Check_grammar:Grammar for internal commands used to check whether internal commands starts on given line.
isCmd(cmdstr)
Returns True if ‘cmdstr’ is internal command. However, it doesn’t check whether ‘cmdstr’ is valid, as it uses ‘command checking’ grammar that usually parses only beginning of the ‘cmdstr’ for command keywords.
runcode(code)

Execute a code object.

When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised.

A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal with it.

runsource(source, filename='<input>', symbol='single', line_offset=0)

Compile and run some source in the interpreter.

Argument ‘lineoffset’ is number of lines processed before this source code. It’s used to report correct line number for syntax errors when input is read from file.

Other arguments are as for compile_command().

One several things can happen:

1) The input is incorrect; compile_command() raised an exception (SyntaxError or OverflowError). A syntax traceback will be printed by calling the showsyntaxerror() method.

2) The input is incomplete, and more input is required; compile_command() returned None. Nothing happens.

3) The input is complete; compile_command() returned a code object. The code is executed by calling self.runcode() (which also handles run-time exceptions, except for SystemExit).

The return value is True in case 2, False in the other cases (unless an exception is raised). The return value can be used to decide whether to use sys.ps1 or sys.ps2 to prompt the next line.

showsyntaxerror(filename=None, line_offset=0)

Display the syntax error that just occurred.

This doesn’t display a stack trace because there isn’t one.

If a filename is given, it is stuffed in the exception instead of what was there before (because Python’s parser always uses “<string>” when reading from a string).

The output is written by self.writeErr(), below.

showtraceback(internal=False)

Display the exception that just occurred.

We remove the first stack item because it is our own code. If ‘internal’ is True, remove also the last stack item (internal command ‘execute’ method).

The output is written by self.writeErr(), below.

write(data='')

Write a string to standard output.

It writes to UI_TEXT Display (context main) provided by ui_provider.

writeErr(data='')

Write a string to error output.

It writes to UI_TEXT Display (context main.stderr) provided by ui_provider.

Console

class pwc.interpreter.Console(packages=[], locals=None, filename='<console>', ui_provider=None, ui_factory=None)

Closely emulate the behavior of the interactive Python interpreter.

This class builds on InteractiveInterpreter and adds prompting using the familiar sys.ps1 and sys.ps2, and input buffering.

interact(banner=None)

Closely emulate the interactive Python console.

The optional banner argument specify the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not to confuse this with the real interpreter – since it’s so close!).

push(line)

Push a line to the interpreter.

The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter’s runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended. The return value is 1 if more input is required, 0 if the line was dealt with in some way (this is the same as runsource()).

resetbuffer()
Reset the input buffer.
pwc.interpreter.interact(banner=None, readfunc=None, local=None)

Closely emulate the interactive Python interpreter.

This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readline module to enable GNU readline if it is available.

Arguments (all optional, all default to None):

Banner:passed to InteractiveConsole.interact()
Readfunc:if not None, replaces InteractiveConsole.raw_input()
Local:passed to InteractiveInterpreter.__init__()

pwc.Itpl

String interpolation for Python (by Ka-Ping Yee, 14 Feb 2000).

This module lets you quickly and conveniently interpolate values into strings (in the flavour of Perl or Tcl, but with less extraneous punctuation). You get a bit more power than in the other languages, because this module allows subscripting, slicing, function calls, attribute lookup, or arbitrary expressions. Variables and expressions are evaluated in the namespace of the caller.

The itpl() function returns the result of interpolating a string, and printpl() prints out an interpolated string. Here are some examples:

from Itpl import printpl
printpl("Here is a @string.")
printpl("Here is a @module.member.")
printpl("Here is an @object.member.")
printpl("Here is a @functioncall(with, arguments).")
printpl("Here is an @{arbitrary + expression}.")
printpl("Here is an @array[3] member.")
printpl("Here is a @dictionary['member'].")

The filter() function filters a file object so that output through it is interpolated. This lets you produce the illusion that Python knows how to do interpolation:

import Itpl
sys.stdout = Itpl.filter()
f = "fancy"
print "Isn't this @f?"
print "Standard output has been replaced with a @sys.stdout object."
sys.stdout = Itpl.unfilter()
print "Okay, back @to @normal."

Under the hood, the Itpl class represents a string that knows how to interpolate values. An instance of the class parses the string once upon initialization; the evaluation and substitution can then be done each time the instance is evaluated with str(instance). For example:

from Itpl import Itpl
s = Itpl("Here is @foo.")
foo = 5
print str(s)
foo = "bar"
print str(s)

Exceptions

exception pwc.Itpl.ItplError(text, pos)

Functions

pwc.Itpl.filter(file=<open file '<stdout>', mode 'w' at 0x2b8c6a7930b8>)

Return an ItplFile that filters writes to the given file object.

‘file = filter(file)’ replaces ‘file’ with a filtered object that has a write() method. When called with no argument, this creates a filter to sys.stdout.

pwc.Itpl.unfilter(ifile=None)

Return the original file that corresponds to the given ItplFile.

‘file = unfilter(file)’ undoes the effect of ‘file = filter(file)’. ‘sys.stdout = unfilter()’ undoes the effect of ‘sys.stdout = filter()’.

Classes

class pwc.Itpl.Itpl(format, codec='UTF-8', encoding_errors='backslashreplace')

Class representing a string with interpolation abilities.

Upon creation, an instance works out what parts of the format string are literal and what parts need to be evaluated. The evaluation and substitution happens in the namespace of the caller when str(instance) is called.

__init__(format, codec='UTF-8', encoding_errors='backslashreplace')

The single mandatory argument to this constructor is a format string.

The format string is parsed according to the following rules:

  1. A dollar sign and a name, possibly followed by any of:
    • an open-paren, and anything up to the matching paren
    • an open-bracket, and anything up to the matching bracket
    • a period and a name

    any number of times, is evaluated as a Python expression.

  2. A dollar sign immediately followed by an open-brace, and anything up to the matching close-brace, is evaluated as a Python expression.

  3. Outside of the expressions described in the above two rules, two dollar signs in a row give you one literal dollar sign.

Optional arguments:

Codec:a string containing the name of a valid Python codec.
Encoding_errors:
 a string with a valid error handling policy. See the codecs module documentation for details.

These are used to encode the format string if a call to str() fails on the expanded result.

_str(glob, loc)

Evaluate to a string in the given globals/locals.

The final output is built by calling str(), but if this fails, the result is encoded with the instance’s codec and error handling policy, via a call to out.encode(self.codec,self.encoding_errors)

__str__()
Evaluate and substitute the appropriate parts of the string.
class pwc.Itpl.ItplNS(format, globals, locals=None, codec='utf_8', encoding_errors='backslashreplace')

Class representing a string with interpolation abilities.

This inherits from Itpl, but at creation time a namespace is provided where the evaluation will occur. The interpolation becomes a bit more efficient, as no traceback needs to be extracte. It also allows the caller to supply a different namespace for the interpolation to occur than its own.

__init__(format, globals, locals=None, codec='utf_8', encoding_errors='backslashreplace')

ItplNS(format,globals[,locals]) -> interpolating string instance.

This constructor, besides a format string, takes a globals dictionary and optionally a locals (which defaults to globals if not provided).

For further details, see the Itpl constructor.

class pwc.Itpl.ItplFile(file)
A file object that filters each write() through an interpolator.

pwc.stdcmd

class pwc.stdcmd.ShowExtender(controller)
Base class for all PowerConsole SHOW command extenders.