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__)
An exception generated directly by PowerConsole.
All exceptions thrown by PowerConsole should be derived from this class.
“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
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:
Base class for all PowerConsole built-in commands.
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:
- IntType is converted to arg=value
- String types are converted to arg=’value’ using correct quotation for given value.
- 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')
Return locals from specified frame.
‘depth’ is number of frames up in stack; 0 means one frame above caller.
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)
Return grammar for command.
Descendant has to override it.
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.
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.
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. |
Returns the command name.
By default, the name is lowercased class name without ‘cmd’ prefix (if it’s present).
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.
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’. |
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.
Default Display.
Supports all defined display interfaces.
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. |
---|
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.
Display list of objects.
Uses Visitor pattern to write out the object. If object doesn’t supports Visitors, then str() representation is written.
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. |
Base/mixin class for object visitors.
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.
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.
Name prefix for attributes/methods that define content for help topics.
HELP_PREFIX = ‘help_’
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.
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.
Return help for ‘topic’.
By default, it returns attribute with name matching HELP_PREFIX+topic.
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.
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.
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. |
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.
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.
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.
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 a string to standard output.
It writes to UI_TEXT Display (context main) provided by ui_provider.
Write a string to error output.
It writes to UI_TEXT Display (context main.stderr) provided by ui_provider.
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.
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 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()).
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__() |
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)
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.
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()’.
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.
The single mandatory argument to this constructor is a format string.
The format string is parsed according to the following rules:
any number of times, is evaluated as a Python expression.
A dollar sign immediately followed by an open-brace, and anything up to the matching close-brace, is evaluated as a Python expression.
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.
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)
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.
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.