Pycopia core package

These are modules that provide core functionality to the rest of the packages, but also contains more general modules that may be used independently.

Translate paths to and from various platforms.

Using cygwin on Windows presents the small problem of translating NT paths to cygwin paths for some applications.

Object oriented asynchronous IO.

class pycopia.asyncio.AsyncClientHandler(sock, addr)[source]
close()[source]
closed
error_handler()[source]
exception_handler(ex, val, tb)[source]
fileno()[source]
hangup_handler()[source]
initialize()[source]
pri_handler()[source]
priority()[source]
read_handler()[source]
readable()[source]
writable()[source]
write(data)[source]
write_handler()[source]
class pycopia.asyncio.AsyncIOHandler(fo)[source]
close()[source]
error_handler()[source]
exception_handler(ex, val, tb)[source]
fileno()[source]
initialize()[source]
read_handler()[source]
readable()[source]
writable()[source]
write(data)[source]
write_handler()[source]
class pycopia.asyncio.AsyncServerHandler(sock, workerclass)[source]
close()[source]
closed
fileno()[source]
priority()[source]
read_handler()[source]
readable()[source]
writable()[source]
class pycopia.asyncio.AsyncWorkerHandler(sock, addr)[source]
close()[source]
closed
error_handler()[source]
exception_handler(ex, val, tb)[source]
fileno()[source]
hangup_handler()[source]
initialize()[source]
inq()[source]

How many bytes are still in the kernel’s input buffer?

outq(sock)[source]

How many bytes are still in the kernel’s output buffer?

pri_handler()[source]
priority()[source]
read_handler(size=4096)[source]
readable()[source]
writable()[source]
write(data)[source]
write_handler()[source]
exception pycopia.asyncio.ExitNow[source]
class pycopia.asyncio.Poll[source]

Object oriented interface to epoll.

Register objects that implement the PollerInterface in the singleton instance.

clear()
error_handler()[source]
exception_handler(ex, val, tb)[source]
fileno()[source]
loop(timeout=-1.0, callback=NULL)[source]
modify(obj)[source]
poll(timeout=-1.0)[source]
priority()[source]
read_handler()[source]
readable()[source]
register(obj)[source]
register_fd(fd, flags, callback)[source]
register_idle(callback)[source]
unregister(obj)[source]
unregister_all()[source]
unregister_fd(fd)[source]
unregister_idle(handle)[source]
writable()[source]
class pycopia.asyncio.PollerInterface[source]
error_handler()[source]
exception_handler(ex, val, tb)[source]
fileno()[source]
hangup_handler()[source]
pri_handler()[source]
priority()[source]
read_handler()[source]
readable()[source]
writable()[source]
write_handler()[source]
class pycopia.asyncio.SIGIOHandler[source]
get(handle)[source]
off()[source]
on()[source]
register(callback, *args)[source]
unregister(handle)[source]
pycopia.asyncio.register(obj)
pycopia.asyncio.register_asyncio(obj)[source]
pycopia.asyncio.set_asyncio(fd_or_obj)[source]

Sets io object to use SIGIO.

pycopia.asyncio.start_sigio()[source]
pycopia.asyncio.stop_sigio()[source]
pycopia.asyncio.unregister(obj)
pycopia.asyncio.unregister_asyncio(obj)[source]
class pycopia.basicconfig.ConfigHolder(init={}, name=None)[source]

ConfigHolder() Holds named configuration information. For convenience, it maps attribute access to the real dictionary. This object is lockable, use the ‘lock’ and ‘unlock’ methods to set its state. If locked, new keys or attributes cannot be added, but existing ones may be changed.

pycopia.basicconfig.check_config(filename) → bool[source]

Check is a config file can be read without errors and contains something.

class pycopia.benchmarks.FunctionTimer(iterations=10000)[source]

A class to test run times of callable objects. Use for simple benchmarks, and to characterize baseline performance.

pycopia.cliutils.get_text(prompt='', msg=None, input=<built-in function raw_input>)[source]

Prompt user to enter multiple lines of text.

pycopia.cliutils.get_input(prompt='', default=None, input=<built-in function raw_input>)[source]

Get user input with an optional default value.

pycopia.cliutils.choose(somelist, defidx=0, prompt='choose', input=<built-in function raw_input>, error=<function default_error at 0x300d050>)[source]

Select an item from a list. Returns the object selected from the list index.

pycopia.cliutils.choose_value(somemap, default=None, prompt='choose', input=<built-in function raw_input>, error=<function default_error at 0x300d050>)[source]

Select an item from a mapping. Keys are indexes that are selected. Returns the value of the mapping key selected.

pycopia.cliutils.choose_key(somemap, default=0, prompt='choose', input=<built-in function raw_input>, error=<function default_error at 0x300d050>)[source]

Select a key from a mapping. Returns the key selected.

pycopia.cliutils.choose_multiple_from_map(somemap, chosen=None, prompt='choose multiple', input=<built-in function raw_input>, error=<function default_error at 0x300d050>)[source]

Choose multiple items from a mapping. Returns a mapping of items chosen. Type in the key to select the values.

pycopia.cliutils.edit_text(text, prompt='Edit text')[source]

Run $EDITOR on text. Defaults to vim.

pycopia.cliutils.print_menu_list(clist, lines=75, columns=132)[source]

Print a list with leading numeric menu choices. Use two columns in necessary.

pycopia.cliutils.print_menu_map(mapping, lines=75, columns=132)[source]

Print a list with leading numeric menu choices. Use two columns in necessary.

class pycopia.combinatorics.KeywordCounter(**kwargs)[source]

Instantiate this as you would any callable with keyword arguments, except that the keyword values should be a list of possible values. When you iterate over it it will return a dictionary with values cycle through the set of possible values.

class pycopia.combinatorics.ListCounter(lists)[source]

An iterator that counts through its list of lists.

pycopia.combinatorics.combinations(n, r)

nCr = n! / ( (n-r)! * r! )

pycopia.combinatorics.fact(x)

factorial(x) return x!

pycopia.combinatorics.factorial(x)[source]

return x!

pycopia.combinatorics.get_permutation(seq, index)[source]

Returns the <index>th permutation of <seq>

pycopia.combinatorics.nCr(n, r)[source]

nCr = n! / ( (n-r)! * r! )

pycopia.combinatorics.nPr(n, r)[source]

nPr = n! / (n-r)!

pycopia.combinatorics.permutations(n, r)

nPr = n! / (n-r)!

pycopia.combinatorics.prune(maxN, sets, chooser=<function prune_end at 0x5c53b90>)[source]

Prune a collection of sets such that number of combinations is less than or equal to maxN. Use this to set an upper bound on combinations and you don’t care if you “hit” all combinations. This simple algorithm basically reduces the number of entries taken from the largest set. If then are equal numbered, then removal is left to right.

maxN is the maximum number of combinations. sets is a list of lists containing the items to be combined. chooser implements the pruning policy. It should be a function taking a number, N, and a list and returning a new list with N elements.

pycopia.daemonize.daemonize(logfile=None, pidfile=None)[source]

This forks the current process into a daemon. Takes an optional file-like object to write stdout and stderr to. Preferrable this will be a logfile.ManagedLog object so that your disk does not fill up.

pycopia.devhelpers.edit(modname)[source]

Opens the $XEDITOR with the given module source file (if found).

pycopia.devhelpers.edit_import_line(importline)[source]

Find the module referenced by the import source line and open in editor.

pycopia.devhelpers.exec_editor(*names)[source]

Runs your configured editor on a supplied list of files. Uses exec, there is no return!

pycopia.devhelpers.find_from_package(pkgname, modname)[source]
pycopia.devhelpers.find_package(packagename, searchpath=None)[source]
pycopia.devhelpers.find_source_file(modname, path=None)[source]
pycopia.devhelpers.find_source_file_from_import_line(line)[source]
pycopia.devhelpers.get_editor()[source]
pycopia.devhelpers.get_object_name(object)[source]
pycopia.devhelpers.get_viewer()[source]
pycopia.devhelpers.module_from_path(fname)[source]

Find and return the module name given a full path name. Return None if file name not in the package path.

pycopia.devhelpers.open_chm(search)[source]

Opens the given search term with a CHM viewer.

pycopia.devhelpers.open_file(filename)[source]
pycopia.devhelpers.open_url(url)[source]

Opens the given URL in an external viewer.

pycopia.devhelpers.pyterm(filename='', interactive=1)[source]
pycopia.devhelpers.python_command(name, interactive=1)[source]
pycopia.devhelpers.run_config(cfstring, param)[source]
pycopia.devhelpers.show_chm_doc(object, chooser=None)[source]
pycopia.devhelpers.showdoc(object, chooser=None)
pycopia.devhelpers.view(modname)[source]

Opens the $[X]VIEWER with the given module source file (if found).

pycopia.devhelpers.xterm(cmd='/bin/sh')[source]

Then environ module defines the Environ class. The Environ class simulates a shell environment that provides methods analogous to shell commands that manipulate the environment. Also, variable expansion is performed when setting new values.

class pycopia.environ.Environ[source]

Environ is a dictionary (like os.environ) that does automatic variable expansion when setting new elements. It supports an extra method called ‘export’ that takes strings of the form ‘name=value’ that may be used to set assign variable names. The ‘expand’ method will return a string with variables expanded from the values contained in this object.

expand(string)[source]

Pass in a string that might have variable expansion to be performed (e.g. a section that has $NAME embedded), and return the expanded string.

export('name=value')[source]

Works like the export command in the bash shell. assigns the name on the left of the equals sign to the value on the right, performing variable expansion if necessary.

inherit([dict])[source]

Works like the ‘update’ method, but defaults to updating from the system environment (os.environ).

This module implements a Finite State Machine (FSM) with two stacks. The FSM is fairly simple. It is useful for small parsing tasks.

class pycopia.fsm.FSM(initial_state=0)[source]

This class is a Finite State Machine (FSM). You set up a state transition table which is the association of:

(input_symbol, current_state) --> (action, next_state)

When the FSM matches a pair (current_state, input_symbol) it will call the associated action. The action is a function reference defined with a signature like this:

def f (input_symbol, fsm):

and pass as parameters the input symbol, and the FSM instance itself. The action function may produce output and update the stack.

add_default_transition(action, next_state)

This sets the default transition. If the FSM cannot match the pair (input_symbol, current_state) in the transition table then this is the transition that will be returned. This is useful for catching errors and undefined states. The default transition can be removed by calling add_default_transition (None, None). If the default is not set and the FSM cannot match the input_symbol and current_state then it will raise an exception (see process()).

add_expression(expression, state, action, next_state, flags=0)[source]

Adds a transition that activates if the input symbol matches the regular expression. The action callable gets a match object instead of the symbol.

add_transition(input_symbol, state, action, next_state)[source]

This adds an association between inputs and outputs. (input_symbol, current_state) –> (action, next_state) The action may be set to None. The input_symbol may be set to None.

add_transition_list(list_input_symbols, state, action, next_state)[source]

This adds lots of the same transitions for different input symbols. You can pass a list or a string. Don’t forget that it is handy to use string.digits, string.letters, etc. to add transitions that match those character classes.

get_transition(input_symbol, state)[source]

This tells what the next state and action would be given the current state and the input_symbol. This returns (action, new state). This does not update the current state nor does it trigger the output action. If the transition is not defined and the default state is defined then that will be used; otherwise, this throws an exception.

process(input_symbol)[source]

This causes the fsm to change state and call an action: (input_symbol, current_state) –> (action, next_state). If the action is None then no action is taken, and only the current state is changed.

reset()[source]

overrideable user reset.

set_default_transition(action, next_state)[source]

This sets the default transition. If the FSM cannot match the pair (input_symbol, current_state) in the transition table then this is the transition that will be returned. This is useful for catching errors and undefined states. The default transition can be removed by calling add_default_transition (None, None). If the default is not set and the FSM cannot match the input_symbol and current_state then it will raise an exception (see process()).

step(token)[source]

This causes the fsm to change state and call an action. (token, current_state) –> (action, next_state) If the action is None then no action is taken, only the current state is changed.

pycopia.fsm.make_states(*args)[source]

converts an argument list of strings to a list of Enum. Use as state transitions.

GUI helpers for interactive use.

A Globally Unique Identifier object. Mostly stolen from ASPN snippet.

class pycopia.guid.GUID(guid=None)[source]

A globally unique identifier that combines ip, time, and random bits. Since the time is listed first, you can sort records by guid. You can also extract the time and ip if needed.

GUIDs make wonderful database keys. They require no access to the database (to get the max index number), they are extremely unique, and they sort automatically by time. GUIDs prevent key clashes when merging two databases together, combining data, or generating keys in distributed systems.

ip()[source]

Extracts the ip portion out of the guid and returns it as a string like 10.10.10.10

time()[source]

Extracts the time portion out of the guid and returns the number of milliseconds since the epoch

class pycopia.ipv4.IPAddressSet[source]
class pycopia.ipv4.IPRange(start, end)[source]
next()
class pycopia.ipv4.IPv4(address, mask=None)[source]

Store an IP addresss. Computes the network, host, and broadcast address on demand.

Usage:

ipaddress = IPv4(address, [mask])

Supply an address as an integer, dotted-quad string, list of 4 integer octets, or another IPv4 object. A netmask may optionally be supplied. It defaults to a classful mask appropriate for its class. the netmask may be supplied as integer, dotted quad, or slash (e.g. /24) notation. The mask may optionally be part of the IP address, in slash notation. if an IPv4 object is initialized with another IPv4 object, the address and mask are taken from it. In the case that a mask is obtained from the address parameter, the mask parameter will be ignored.

For example:

ip = IPv4("10.1.1.2")
ip = IPv4("10.1.1.2", "255.255.255.0")
ip = IPv4("10.1.1.2/24") # note that if a mask value was supplied,
                         # it would be ignored.

Raises ValueError if the string representation is malformed, or is not an integer.

Class attributes that you may set or read are:

address   = 32 bit integer IP address
mask      = 32 bit integer mask
maskbits  = number of bits in the mask

additional attributes that are read-only (UNDEFINED for /32 IPV4 objects!):

network             = network number, host part is zero.
host (or hostpart)  = host number, network part is zero.
broadcast           = directed broadcast address, host part is all ones.
firsthost           = What would be the first address in the subnet.
lasthost            = What would be the last address in the subnet.

Methods:

copy() - Return a copy of this IPv4 address.
nextnet() - Increments the IP address into the next network range.
previousnet() - Decrements the IP address into the previous network range.
nexthost() - Increments this IP address object's host number.
previoushost() - Decrements this IP address object's host number.
set_to_first() - Set the IP address to the first address in the subnet.
set_to_last() - Set the IP address to the last address in the subnet.
getStrings() - return a 3-tuple of address, mask and broadcast as dotted
               quad strings.

Operators:

An IPv4 object can be used in a "natural" way with some python
operators.  It behaves as a sequence object when sequence
operators are applied to it.
For example::

    ip = ipv4.IPv4("192.168.1.0", "255.255.255.248")
    ip[2] returns 2nd host in subnet.
    ip[-1] returns broadcast address.
    ip[0] returns network.
    ip[1:-1] returns list of IPv4 objects from first to last host.
    len(ip) returns number of hosts in network range, including net
            and broadcast.
    if ip3 in ip:     # test for inclusion in subnet
        print "In range"

You may also perform some arithmetic operators::

    ip2 = ip + 2 # assigns ip2 to new IPv4 object two hosts greater than ip.
    ip2 > ip # returns true (can compare addresses)
    int(ip) # return IPv4 object address as integer
    hex(ip) # return IPv4 object address as hexadecimal string
CIDR

Returns string in CIDR notation.

address

whole address

address_mask_broadcast

Returns a 3-tuple of address, mask, and broadcast address as dotted-quad string.

broadcast
cidr()[source]

Returns string in CIDR notation.

copy()[source]
firsthost

first host in range

getStrings()[source]

Returns a 3-tuple of address, mask, and broadcast address as dotted-quad string.

gethost()[source]

Resolve this IP address to a canonical name using gethostbyaddr.

host

host part

hostname

associated host name

hostpart

host part

lasthost

last host in range

mask

address mask

maskbits

CIDR mask bits

network

network part

nexthost(increment=1)[source]

Increments this IP address object’s host number. It will overflow into the next network range. It will not become a broadcast or network address.

nextnet(increment=1)[source]

Increments the IP address into the next network range, keeping the host part constant. Default increment is 1, but optional increment parameter may be used.

previoushost(decrement=1)[source]

Decrements this IP address object’s host number. It will underflow into the next network range. It will not become a broadcast or network address.

previousnet(decrement=1)[source]

Decrements the IP address into the next network range, keeping the host part constant. Default decrement is 1, but optional decrement parameter may be used.

set_to_first()[source]

Set the address to the first host in the network.

set_to_last()[source]

Set the address to the last host in the network.

pycopia.ipv4.dqtoi(dq)[source]

Return an integer value given an IP address as dotted-quad string. You can also supply the address as a a host name.

pycopia.ipv4.findnet(ip, ipnets)[source]
pycopia.ipv4.ipnetrange(startnet, number, increment=1)[source]

Return a list of consecutive networks, starting from initial network and mask, keeping the mask constant.

Usage::
ipnetrange(startnet, number, [increment])
Where::
startnet is an IP address where the range will start. number is the number of IP networks in the range optional increment will skip that number of nets.
pycopia.ipv4.iprange(startip, number, increment=1)[source]

Return a list of consequtive IP address strings.

Usage::
iprange(startip, number)
Where::
startip is an IP address to start from. number is the number of IP addresses in the returned list.
pycopia.ipv4.itodq(addr)[source]

Return a dotted-quad string given an integer.

pycopia.ipv4.nametoi(name)[source]

Resolve a name and return the IP address as an integer.

pycopia.ipv4.netrange(startnet, number, increment=1)[source]

Return a list of consecutive networks, starting from initial network and mask, keeping the mask constant.

Usage::
netrange(startnet, number, [increment])
Where::
startnet is an IP address where the range will start. number is the number of IP networks in the range. An optional increment will set the stride (count by <increment> nets).
pycopia.ipv4.resolve(host, mask=None)[source]

Resolve a hostname to an IPv4 object. An optional mask value may me supplied.

pycopia.ipv4.sortnets(l)[source]

Config object backed by a JSON encoded file. This module is compatible with plistconfig module. The only difference is the on-disk storage format.

class pycopia.jsonconfig.AutoAttrDict(*args, **kwargs)[source]

A dictionary with attribute-style access and automatic container node creation.

add_container(name)[source]
copy()[source]
expand(value)[source]
tofile(path_or_file)[source]
pycopia.jsonconfig.dump(conf, fo)[source]
pycopia.jsonconfig.dumps(conf)[source]
pycopia.jsonconfig.get_config(filename=None, init=None)[source]

Get an existing or new json config object.

Optionally initialize from another dictionary.

pycopia.jsonconfig.get_encoder()[source]
pycopia.jsonconfig.is_modified(conf)[source]
pycopia.jsonconfig.load(fo)[source]
pycopia.jsonconfig.loads(s)[source]
pycopia.jsonconfig.read_config(path_or_file)[source]

Read a JSON config file.

pycopia.jsonconfig.reset_modified(conf)[source]
pycopia.jsonconfig.write_config(conf, path_or_file)[source]

Write a JSON config file.

Managing logfile rotation. A ManagedLog object is a file-like object that rotates itself when a maximum size is reached.

class pycopia.logfile.LogFile(name, mode='w', maxsize=360000)[source]

LogFile(name, [mode=”w”], [maxsize=360000]) Opens a new file object. After writing <maxsize> bytes a SizeError will be raised.

note(text)[source]

Writes a specially formated note text to the file.The note starts with the string ‘n#*=’ so you can easily filter them.

rotate()[source]
write(data)[source]
class pycopia.logfile.ManagedLog(name, maxsize=360000, maxsave=9)[source]

ManagedLog(name, [maxsize=360000], [maxsave=9]) A ManagedLog instance is a persistent log object. Write data with the write() method. The log size and rotation is handled automatically.

note(data)[source]
rotate()[source]
write(data)[source]
written()[source]
class pycopia.logfile.ManagedStdio(name, maxsize=360000, maxsave=9)[source]
write(data)[source]
exception pycopia.logfile.SizeError[source]
pycopia.logfile.open(name, maxsize=360000, maxsave=9)[source]
pycopia.logfile.rotate(fileobj, maxsave=9)[source]
pycopia.logfile.shiftlogs(basename, maxsave)[source]
pycopia.logfile.writelog(logobj, data)[source]
pycopia.makepassword.getrandomlist()[source]

get a list of random bytes from Linux’s cryptographically strong random number generator.

pycopia.makepassword.getrandomwords(N=2)[source]

Get a word at random from the system word list. The psuedo-random number generator is suitable for this purpose.

pycopia.makepassword.hashword(plaintext)[source]

Munge a plaintext word into something else. Hopefully, the result will have some mnemonic value.

class pycopia.methodholder.MethodHolder(method=None, **kwargs)[source]

MethodHolder(method) Allows for the delayed invocation of methods, and easy introspection of formal parameters for user interfaces.

methodname

Method name

Implements a netstring object, as described in:

http://cr.yp.to/proto/netstrings.txt

User objects from passwd entries. Funtionally enchanced PWEntry object is better than the pwd_passwd structure, and is pickle-able as well.

Config object backed by a property list file. A property list file is an XML format text file using Apple’s Property List DTD (PropertyList-1.0.dtd).

class pycopia.plistconfig.AutoAttrDict(*args, **kwargs)[source]

A dictionary with attribute-style access and automatic container node creation.

pycopia.plistconfig.get_config(filename=None, init=None)[source]

Get an existing or new plist config object.

Optionally initialize from another dictionary.

pycopia.plistconfig.read_config(path_or_file)[source]

Read a property list config file.

pycopia.plistconfig.write_config(conf, path_or_file)[source]

Write a property list config file.

Implment an abstraction of a protocol state machine.

class pycopia.protocols.Protocol(eol=None)[source]

Implement the actions for the state machine. Add bound methods to it.

EOL = '\n'
close()[source]
initialize(states)[source]

Fill this in with state transitions.

log(*args)[source]
reset()[source]
run(iostream, data=None)[source]
start()[source]
step(iostream, data=None)[source]
writeln(data)[source]
exception pycopia.protocols.ProtocolError[source]

Raise when the protocol transition is invalid.

exception pycopia.protocols.ProtocolExit[source]

Raise when the protocol completes.

class pycopia.protocols.StateMachine(initial_state=Enum(0, 'RESET'))[source]
ANY = Enum(-1, 'ANY')
RESET = Enum(0, 'RESET')
add(symbol, state, action, next_state)[source]
add_any(state, action, next_state)[source]
add_exact(symbol, state, action, next_state)[source]
add_glob(expression, state, action, next_state)[source]
add_list(expression_list, state, action, next_state)[source]
add_regex(expression, state, action, next_state, ignore_case=False, multiline=False)[source]
pop()[source]
popalt()[source]
push(v)[source]
pushalt(v)[source]
reset()[source]
set_default_transition(action, next_state)[source]
step(symbol)[source]
pycopia.protocols.is_exact(pattern)[source]
pycopia.protocols.transition_error(text)[source]

Analyze regular expressions. Parse the regular expressions and construct a string that will match it, or a string that will not match it. The matching string will have some randomness to introduce some characteristics of Monte Carlo testing. For complex REs, it’s not likely that the same string will be produced twice.

exception pycopia.re_inverse.Error[source]
exception pycopia.re_inverse.GeneratorError[source]
class pycopia.re_inverse.StringGenerator(regexp, N=10, bad=False, flags=0)[source]
next()[source]
exception pycopia.re_inverse.UnhandledOpError[source]
pycopia.re_inverse.compile(regexp, flags=0)[source]
pycopia.re_inverse.get_flags(flags)[source]
pycopia.re_inverse.get_substitute(category, inverse)[source]
pycopia.re_inverse.make_match_string(regexp, flags=0)[source]

Given a string that is a regular expression, return a string (perhaps with some randomness) that is certain to produce a match (we hope).

pycopia.re_inverse.make_nonmatch_string(regexp, flags=0)[source]

Given a string that is a regular expression, return a string (perhaps with some randomness) that is certain to NOT produce a match.

A library for scheduling callback functions using SIGALRM. When used, this module “owns” SIGALRM, and all timing functions associated with it. This means that you should not use the stock time.sleep() function when using this module. Instead, use get_scheduler().sleep(x) to sleep.

pycopia.scheduler.get_scheduler()[source]

I shared memory object for IPC support using coprocesses.

A parser for splitting a simple POSIX shell syntax.

class pycopia.shparser.CommandSplitter[source]
feedline(text)[source]
class pycopia.shparser.ShellParser(cb=None)[source]

ShellParser([callback]) Feed the parser, callback gets an argv list for each completed suite.

VARNAME = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_?'
feed(text)[source]
feedline(text)[source]
interact(ps1='shparse> ', ps2='more> ')[source]
parseFile(fo)[source]
parseurl(url)[source]
reset()[source]
pycopia.shparser.get_command_splitter()[source]

This module can be used to generate python source code. It has an interface similar to the “new” module.

class pycopia.sourcegen.SourceFile(fo=None, bangline=None)[source]

Represents a python source file.

class pycopia.sourcegen.SourceGen(outfile, bangline=None)[source]

An instance of this SourceGen class is a factory for generating python source code, by writing to a file object.

class pycopia.sourcegen.TextHolder(text, level=0)[source]

Holds arbitrary text for the source file. Caller must assure the text is syntactically correct Python.

pycopia.sourcegen.genClass(klassname, parents, attribs=None, doc=None, methods=None)[source]

Return a string of Python source code defineing a class object.

Where:

name = class name (string)
parents = tuple of parent class objects or strings.
attribs = class-global attributes to define, contained in a dictionary.
doc = a doc string (optional)
methods = list of methods strings.
class pycopia.ssmtpd.SMTPServer(port=9025, logfile=None, parser=None)[source]

SMTPDServer(port=25, logfile=None, parser=None) An SMTP server object that listens on the specified port. If a ‘logfile’ file-like object is supplied the SMTP conversation will be written to it. If a parser object is supplied then any message body recieved will be automatically parsed, and any errors returned to the client.

close()[source]

Closes the server (stops listening).

get_conversation()[source]

Fetches the conversation list-object from this server.

get_envelopes()[source]

Returns the stored list of Envelope objects, clearing the list.

poll(timeout=0, conversation=None)[source]

Polls the server, waiting timeout seconds (or forever if zero). Returns one message Envelope object if available.

run(cb=None, timeout=0, conversation=None)[source]

Runs the SMTP server (single thread). If a list object is passed in as the ‘conversation’ then the SMTP conversation will be stored in it. If a callback function is supplied then it will be called for each message Envelope recieved (with the Envelope object as a parameter).

pycopia.ssmtpd.get_smtpd(port=9025, logfile=None, parser=None)[source]

Factory function to return an SMTP server object, listening on the specified port. The serverhost is where the SMTP port (25) will be listening.

pycopia.ssmtpd.kill_smtpd(port=9025)[source]

Stops the SMTPDListener.

Same as Python’s stock random module, except use the system random source by default.

class pycopia.table.GenericTable(obj=None, default=None, title=None, width=80)[source]

GenericTable([initializer], [default=None]) A two-dimensional table of objects.

Match plain strings like they were re module objects.

The StringExpression object implements a subset of re compile expressions. This allows for a more consistent interface for the match types. Since string.find is about 10 times faster than an RE search with a plain string, this should speed up matches in that case by about that much, while keeping a consistent interface.

Utility methods that perform various manipulations on text files.

pycopia.texttools.sub_file(template_fo, dest_fo, subdict)[source]
template_fo
is a file object for the template file. This file contains unique strings that must match the keys in the subsititution dictionary (sustitutedict).
dest_fo
is a file object that will have the template file with substitutions written to it.
subdict
is a dictionary with keys that must match the tag strings in the template file. The value of that dictionary entry will be substituted for the tag in the destination file.

Measurement

Objects for dealing with measurement values with units and supports unit conversion.

class pycopia.physics.physical_quantities.PhysicalQuantity(value, unit=None, space=u' ')[source]

Physical quantity with units

Constructor:

  • PhysicalQuantity(value, unit), where value is a number of arbitrary type and `unit is a string containing the unit name.
  • PhysicalQuantity(string), where string contains both the value and the unit. This form is provided to make interactive use more convenient.

PhysicalQuantity instances allow addition, subtraction, multiplication, and division with each other as well as multiplication, division, and exponentiation with numbers. Addition and subtraction check that the units of the two operands are compatible and return the result in the units of the first operand. A limited set of mathematical functions (from module Numeric) is applicable as well:

sqrt – equivalent to exponentiation with 0.5.

sin, cos, tan – applicable only to objects whose unit is compatible
with ‘rad’.
convertToUnit(unit)[source]

Changes the unit to unit and adjusts the value such that the combination is equivalent. The new unit is by a string containing its name. The new unit must be compatible with the previous unit of the object.

cos()[source]
inBaseUnits()[source]
inUnitsOf(*units)[source]

Returns one or more PhysicalQuantity objects that express the same physical quantity in different units. The units are specified by strings containing their names. The units must be compatible with the unit of the object. If one unit is specified, the return value is a single PhysicalObject. If several units are specified, the return value is a tuple of PhysicalObject instances with with one element per unit such that the sum of all quantities in the tuple equals the the original quantity and all the values except for the last one are integers. This is used to convert to irregular unit systems like hour/minute/second. The original object will not be changed.

isCompatible(unit)[source]
nospace()[source]
sin()[source]
sqrt()[source]
tan()[source]
usespace(space=u' ')[source]
class pycopia.physics.physical_quantities.PhysicalUnit(names, factor, powers, offset=0)[source]
conversionFactorTo(other)[source]
conversionTupleTo(other)[source]
isAngle()[source]
isCompatible(other)[source]
isDimensionless()[source]
name()[source]
setName(name)[source]
pycopia.physics.physical_quantities.isPhysicalQuantity(x)[source]

Returns 1 if x is an instance of PhysicalQuantity.

pycopia.physics.physical_quantities.isPhysicalUnit(x)[source]

General conversion functions.

Convert units from one to another. Generally you can use a PhysicalQuantity object to do linear conversions. But that doesn’t handle logarithmic units yet.

All voltages are RMS values.

Internet protocol support

Modules for working with Internet protocols.

class pycopia.inet.httputils.Comment(*items)[source]

An http header comment. This is extended a little bit to support semi-colon delimited fields.

class pycopia.inet.httputils.Cookie(_value=None, **kwargs)[source]

A Cookie class. This actually holds a collection of RawCookies.

class pycopia.inet.httputils.CookieJar(filename=None, defaultdomain=None)[source]

A collection of cookies. May be used in a client or server context.

class pycopia.inet.httputils.EntityTag(tag, weak=0)[source]

Entity tags are used for comparing two or more entities from the same requested resource. HTTP/1.1 uses entity tags in the ETag, If-Match, If-None-Match, and If-Range header fields.

class pycopia.inet.httputils.HTTPDate(date=None, _value=None)[source]

HTTP-date = rfc1123-date | rfc850-date | asctime-date

class pycopia.inet.httputils.HTTPHeader(_value=None, **kwargs)[source]

HTTPHeader. Abstract base class for all HTTP headers.

initialize(**kwargs)[source]

Override this to set the value attribute based on the keyword arguments.

class pycopia.inet.httputils.Headers(arg=None)[source]

Holder for a collection of headers. Should only contain HTTPHeader objects. Optionally initialize with a list of tuples (WSGI style headers).

asStrings()[source]

Return list as copy of self with strings as content. The curl library likes this.

asWSGI()[source]

Return list as copy of self with WSGI style tuples as content.

getall(key)[source]

Return all occurences of key in a list.

class pycopia.inet.httputils.MediaRange(type='*', subtype='*', q=1.0, **kwargs)[source]

MediaRange is an element in an Accept list. Here, a None values means ANY. These are essential MIME types.

class pycopia.inet.httputils.Product(vendor='Mozilla/5.0', version=None)[source]

Product(vendor, [version]) vendor is a vendor string. can contain a version, or not. If not, can supply version separately. version is a version number, as a string.

class pycopia.inet.httputils.QuotedString(val)[source]

QuotedString(data) Represents an HTTP quoted string. Automatically encodes the value.

class pycopia.inet.httputils.RawCookie(name, value, comment=None, domain=None, max_age=None, path=None, secure=0, version=1, expires=None, httponly=False)[source]

A single cookie. Merges Netscape and RFC styles. Used for local storage of a cookie. Use a CookieJar to store a collection.

set_comment(comment)[source]

Optional. Because cookies can contain private information about a user, the Cookie attribute allows an origin server to document its intended use of a cookie. The user can inspect the information to decide whether to initiate or continue a session with this cookie.

set_domain(dom)[source]

Optional. The Domain attribute specifies the domain for which the cookie is valid. An explicitly specified domain must always start with a dot.

set_httponly(val)[source]

Optional. The HttpOnly attribute.

set_max_age(ma)[source]

Optional. The Max-Age attribute defines the lifetime of the cookie, in seconds. The delta-seconds value is a decimal non- negative integer. After delta-seconds seconds elapse, the client should discard the cookie. A value of zero means the cookie should be discarded immediately.

set_path(path)[source]

Optional. The Path attribute specifies the subset of URLs to which this cookie applies.

set_secure(val=1)[source]

Optional. The Secure attribute (with no value) directs the user agent to use only (unspecified) secure means to contact the origin server whenever it sends back this cookie.

set_version(ver)[source]

Required. The Version attribute, a decimal integer, identifies to which version of the state management specification the cookie conforms. For this specification, Version=1 applies.

class pycopia.inet.httputils.UserAgent(_value=None, **kwargs)[source]

see: <http://www.mozilla.org/build/revised-user-agent-strings.html> default value: “Mozilla/5.0 (X11; U; Linux i686; en-US)”

pycopia.inet.httputils.get_header(line)[source]

Factory for getting proper header object from text line.

pycopia.inet.httputils.headerlines(bigstring)[source]

Return list of unfolded header from a chunk of multipart text, and rest of text.

fcgi - a FastCGI/WSGI gateway.

For more information about FastCGI, see <http://www.fastcgi.com/>.

For more information about the Web Server Gateway Interface, see <http://www.python.org/peps/pep-0333.html>.

Example usage:

#!/usr/bin/env python from myapplication import app # Assume app is your WSGI application object from pycopia.inet.fcgi import FCGIServer FCGIServer(app).run()

See the documentation for FCGIServer/Server for more information.

On most platforms, fcgi will fallback to regular CGI behavior if run in a non-FastCGI context. If you want to force CGI behavior, set the environment variable FCGI_FORCE_CGI to “Y” or “y”.

class pycopia.inet.fcgi.FCGIServer(application, procmanager=None, errorhandler=None, environ=None, maxwrite=8192, bindAddress=None, umask=None, idle=NULL, debug=False)[source]

FastCGI server that supports the Web Server Gateway Interface. See <http://www.python.org/peps/pep-0333.html>.

The FastCGI server.

Waits for connections from the web server, processing each request.

handler(req)[source]

Handles WSGI request.

run(timeout=1.0)[source]

The main loop. Exits on SIGHUP, SIGINT, SIGTERM. Returns True if SIGHUP was received, False otherwise.

class pycopia.inet.rfc2822.Comment(item)[source]

A header comment.

class pycopia.inet.rfc2822.Header(name, value)[source]

base class for header objects.

class pycopia.inet.rfc2822.Headers[source]

A Collection of headers. No duplicates allowed here.

class pycopia.inet.rfc2822.Message(header, body=None)[source]

Represents an email message.

class pycopia.inet.rfc2822.QuotedString(val)[source]

QuotedString(data) Represents an quoted string. Automatically encodes the value.

pycopia.inet.rfc2822.formatdate(timeval=None)[source]

Returns time format preferred for Internet standards.

Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123

According to RFC 1123, day and month names must always be in English. If not for that, this code could use strftime(). It can’t because strftime() honors the locale and could generated non-English names.

pycopia.inet.rfc2822.headerlines(bigstring)[source]

Yield unfolded lines from a chunk of text.

pycopia.inet.rfc2822.unfold(s)[source]

Unfold a folded string, keeping line breaks and other white space.

class pycopia.inet.SMTP.Envelope(mail_from=None, rcpt_to=None)[source]

Envelope([mail_from], [recpt_list]) An envelope holds an SMTP conversation from the MAIL FROM command to the end of a DATA part. It may be re-sent by calling the ‘send()’ method with an SMTP connection object. The message body can be parsed by passing in an ‘email’ parser object to the ‘parse()’ method.

add_rcpt(recipient)[source]

Adds a new recipient to the RCPT list.

has_data()[source]

has_data() is true if there is data or message.

parse_data(parser)[source]

Instructs the Envelope to convert its raw ‘data’ attribute to a ‘message’ attribute using the supplied parser object. A ‘message’ attribute is an ‘email’ package Message tree.

send(smtp_client, mail_options=[], rcpt_options=[])[source]

Mails this envelope using the supplied SMTP client object.

set_from(from_address)[source]

Sets the MAIL FROM address for this Envelope.

write(text)[source]

Writes text to the message body.

writeln(text)[source]

Writes text to the message body, adding a newline.

class pycopia.inet.SMTP.SMTP(host='', port=25, bindto=None, logfile=None)[source]

This class manages a connection to an SMTP or ESMTP server.

SMTP objects have the following attributes:

helo_resp
    This is the message given by the server in response to the
    most recent HELO command.

ehlo_resp
    This is the message given by the server in response to the
    most recent EHLO command. This is usually multiline.

does_esmtp
    This is a True value _after you do an EHLO command, if the
    server supports ESMTP.

esmtp_features
    This is a dictionary, which, if the server supports ESMTP,
    will _after you do an EHLO command, contain the names of the
    SMTP service extensions this server supports, and their
    parameters (if any).

    Note, all extension names are mapped to lower case in the
    dictionary.

See each method's docstrings for details.  In general, there is a
method of the same name to perform each SMTP command.  There is also a
method called 'sendmail' that will do an entire mail transaction.
close()[source]

Close the connection to the SMTP server.

connect(host='localhost', port=0, bindto=None, retries=3)[source]

Connect to a host on a given port.

If the hostname ends with a colon (:) followed by a number, and there is no port specified, that suffix will be stripped off and the number interpreted as the port number to use.

Note: This method is automatically invoked by __init__, if a host is specified during instantiation.

data(msg)[source]

SMTP ‘DATA’ command – sends message data to server.

Automatically quotes lines beginning with a period per rfc821. Raises SMTPDataError if there is an unexpected reply to the DATA command; the return value from this method is the final response code received when the all data is sent.

docmd(cmd, args='')[source]

Send a command, and return its response code.

ehlo(name='')[source]

SMTP ‘ehlo’ command. Hostname to send for this command defaults to the FQDN of the local host.

expn(address)[source]

SMTP ‘verify’ command – checks for address validity.

getreply()[source]

Get a reply from the server.

Returns a tuple consisting of:

  • server response code (e.g. ‘250’, or such, if all goes well) Note: returns -1 if it can’t read response code.
  • server response string corresponding to response code (multiline responses are converted to a single, multiline string).

Raises SMTPServerDisconnected if end-of-file is reached.

has_extn(opt)[source]

Does the server support a given SMTP service extension?

helo(name='')[source]

SMTP ‘helo’ command. Hostname to send for this command defaults to the FQDN of the local host.

help(args='')[source]

SMTP ‘help’ command. Returns help text from server.

login(user, password)[source]

Log in on an SMTP server that requires authentication.

The arguments are:
  • user: The user name to authenticate with.
  • password: The password for the authentication.

If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first.

This method will return normally if the authentication was successful.

This method may raise the following exceptions:

SMTPHeloError The server didn’t reply properly to
the helo greeting.
SMTPAuthenticationError The server didn’t accept the username/
password combination.
SMTPException No suitable authentication method was
found.
mail(sender, options=[])[source]

SMTP ‘mail’ command – begins mail xfer session.

noop()[source]

SMTP ‘noop’ command – doesn’t do anything :>

putcmd(cmd, args='')[source]

Send a command to the server.

quit()[source]

Terminate the SMTP session.

rcpt(recip, options=[])[source]

SMTP ‘rcpt’ command – indicates 1 recipient for this mail.

rset()[source]

SMTP ‘rset’ command – resets session.

send(s)[source]

Send string to the server.

sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])[source]

This command performs an entire mail transaction.

The arguments are:

:from_addr:      The address sending this mail.
:to_addrs:       A list of addresses to send this mail to.  A bare
                 string will be treated as a list with 1 address.
:msg:            The message to send.
:mail_options:   List of ESMTP options (such as 8bitmime) for the
                 mail command.
:rcpt_options:   List of ESMTP options (such as DSN commands) for
                 all the rcpt commands.

If there has been no previous EHLO or HELO command this session, this method tries ESMTP EHLO first. If the server does ESMTP, message size and each of the specified options will be passed to it. If EHLO fails, HELO will be tried and ESMTP options suppressed.

This method will return normally if the mail is accepted for at least one recipient. It returns a dictionary, with one entry for each recipient that was refused. Each entry contains a tuple of the SMTP error code and the accompanying error message sent by the server.

This method may raise the following exceptions:

:SMTPHeloError:         The server didn't reply properly to
                        the helo greeting.
:SMTPRecipientsRefused: The server rejected ALL recipients
                        (no mail was sent).
:SMTPSenderRefused:     The server didn't accept the from_addr.
:SMTPDataError:         The server replied with an unexpected
                        error code (other than a refusal of
                        a recipient).

Note: the connection will be open even after an exception is raised.

Example:

>>> import smtplib
>>> s=smtplib.SMTP("localhost")
>>> tolist=["one@one.org","two@two.org","three@three.org","four@four.org"]
>>> msg = '''\
... From: Me@my.org
... Subject: testin'...
...
... This is a test '''
>>> s.sendmail("me@my.org",tolist,msg)
{ "three@three.org" : ( 550 ,"User unknown" ) }
>>> s.quit()

In the above example, the message was accepted for delivery to three of the four addresses, and one was rejected, with the error code 550. If all addresses are accepted, then the method will return an empty dictionary.

starttls(keyfile=None, certfile=None)[source]

Puts the connection to the SMTP server into TLS mode.

If the server supports TLS, this will encrypt the rest of the SMTP session. If you provide the keyfile and certfile parameters, the identity of the SMTP server and client can be checked. This, however, depends on whether the socket module really checks the certificates.

verify(address)[source]

SMTP ‘verify’ command – checks for address validity.

vrfy(address)

SMTP ‘verify’ command – checks for address validity.

exception pycopia.inet.SMTP.SMTPAuthenticationError(code, msg)[source]

Authentication error.

Most probably the server didn’t accept the username/password combination provided.

exception pycopia.inet.SMTP.SMTPConnectError(code, msg)[source]

Error during connection establishment.

exception pycopia.inet.SMTP.SMTPDataError(code, msg)[source]

The SMTP server didn’t accept the data.

exception pycopia.inet.SMTP.SMTPException[source]

Base class for all exceptions raised by this module.

exception pycopia.inet.SMTP.SMTPHeloError(code, msg)[source]

The server refused our HELO reply.

exception pycopia.inet.SMTP.SMTPRecipientsRefused(recipients)[source]

All recipient addresses refused.

The errors for each recipient are accessible through the attribute ‘recipients’, which is a dictionary of exactly the same sort as SMTP.sendmail() returns.

exception pycopia.inet.SMTP.SMTPResponseException(code, msg)[source]

Base class for all exceptions that include an SMTP error code.

These exceptions are generated in some instances when the SMTP server returns an error code. The error code is stored in the smtp_code attribute of the error, and the smtp_error attribute is set to the error message.

exception pycopia.inet.SMTP.SMTPSenderRefused(code, msg, sender)[source]

Sender address refused.

In addition to the attributes set by on all SMTPResponseException exceptions, this sets sender to the string that the SMTP refused.

exception pycopia.inet.SMTP.SMTPServerDisconnected[source]

Not connected to any SMTP server.

This exception is raised when the server unexpectedly disconnects, or when an attempt is made to use the SMTP instance before connecting it to a server.

class pycopia.inet.SMTP.SSLFakeFile(sslobj)[source]

A fake file like object that really wraps a SSLObject.

It only supports what is needed in smtplib.

class pycopia.inet.SMTP.SSLFakeSocket(realsock, sslobj)[source]

A fake socket object that really wraps a SSLObject.

It only supports what is needed in smtplib.

pycopia.inet.SMTP.quoteaddr(addr)[source]

Quote a subset of the email addresses defined by RFC 821.

pycopia.inet.SMTP.quotedata(data)[source]

Quote data for email.

Double leading ‘.’, and change Unix newline ‘n’, or Mac ‘r’ into Internet CRLF end-of-line.

OS Information and interfaces

A set of modules for interfacing with OS specific features.

Linux

Linux /proc data

The devices file.

Interface to the /proc/interrupts file.

Interface to the /proc/mounts file.

Read /proc/net/dev data.

MODULE_DESCRIPTION

class pycopia.OS.Linux.proc.net.netstat.TCPTable[source]

sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode

Routing table via /proc/net/route. Note that the RouteEntry returns values in host byte order, not the network byte order that the kernel file emits.

class pycopia.OS.Linux.proc.net.route.RouteEntry(Iface, Destination=None, Gateway=None, Flags=0, RefCnt=0, Use=0, Metric=0, Mask=None, MTU=0, Window=0, IRTT=0)[source]

Represents a routing table entry.

class pycopia.OS.Linux.proc.net.route.RouteTable[source]

Represents the kernel FIB. Supports sequence operators.

update([filter])[source]

Update the RouteTable with current values. If a filter function is supplied then it will be called with a RouteEntry and must return a true or false value. If true, the RouterEntry will be included in the table. If false, it will not.

The basic SNMP scalars from /proc/net/snmp.

Process info

class pycopia.OS.Linux.procfs.CPUMeasurer(pid=None)[source]

Helper to measure CPU utilization of a process.

class pycopia.OS.Linux.procfs.ProcStat(pid=None)[source]

Status information about a process.

class pycopia.OS.Linux.procfs.ProcStatTable(fmt=u'%(pid)6s %(ppid)6s %(ttyname)6.6s %(cmdline).55s')[source]

ProcStatTable() A collection of all processes running, like the standard ‘ps’ command.

pycopia.OS.Linux.procfs.killall(procname, sig=15)[source]

killall(procname, [signal]) Sends a signal (default SIGTERM) to all processes that match the given name.

pycopia.OS.Linux.procfs.pidof(procname)[source]

pidof(procname) Returns a list of PIDs (integers) that match the given process name.

Devices

rtc.py provides access the the real time clock.

from the Linux Documentation:

All PCs (even Alpha machines) have a Real Time Clock built into them. Usually they are built into the chipset of the computer, but some may actually have a Motorola MC146818 (or clone) on the board. This is the clock that keeps the date and time while your computer is turned off.

However it can also be used to generate signals from a slow 2Hz to a relatively fast 8192Hz, in increments of powers of two. These signals are reported by interrupt number 8. (Oh! So that is what IRQ 8 is for...) It can also function as a 24hr alarm, raising IRQ 8 when the alarm goes off. The alarm can also be programmed to only check any subset of the three programmable values, meaning that it could be set to ring on the 30th second of the 30th minute of every hour, for example. The clock can also be set to generate an interrupt upon every clock update, thus generating a 1Hz signal.

For more information, see /usr/src/linux/Documentation/rtc.txt

class pycopia.OS.Linux.rtc.RTC[source]

RTC() represent the Real Time Clock device on a PC. Some methods require root privileges.

alarm_read()[source]

alarm_read() Returns and rtc_time object. Note that only the hour, minute, and second fields are used.

procinfo()[source]

procinfo() Returns a dictionary with name-value pairs taken from /proc/driver/rtc.

read(amt=None)[source]

read() returns a 2-tuple. (number of interrupts since last read, interrupt status). May block.

reset_epoch()[source]

The default epoch is usually correct, but if it is not this method will reset it to the value read from the device.

time_read()[source]

time_read() Returns an rtc_time object. Note that the RTC driver only fills in the year, month, day, hour, minute, and second fields.

time_tuple()[source]

time_tuple() Returns a tuple suitable for the functions in the time module.

update_interrupt_off()[source]

Turn off update interrupts (one per second)

update_interrupt_on()[source]

Turn on update interrupts (one per second)

class pycopia.OS.Linux.rtc.StopWatch[source]

StopWatch is a low-resolution timer for timing things, such as execution time.

Interface to produce Linux event stream from ascii data.

class pycopia.OS.Linux.event.KeyEventGenerator(device, keymap={'@': 515, 'xc2xa3': 1540, 'xc2xa5': 1542, '|': 555, '~': 553, '[': 26, ']': 27, '{': 538, '_': 524, '^': 519, '!': 514, '`': 41, '#': 516, '"': 552, '%': 518, '$': 517, "'": 40, '&': 520, ')': 523, '(': 522, '+': 525, '*': 521, '-': 12, ', ': 51, '/': 53, '.': 52, '}': 539, ';': 39, ':': 551, '=': 13, '<': 563, '?': 565, '>': 564})[source]

ASCII in, events out. Call an instance with a string.

Interface to /dev/input/eventX devices. This module provides base classes and constant values for accessing the Linux input interface. This includes keyboard, mouse, joystick, and a general event interface.

class pycopia.OS.Linux.Input.Event(time=0.0, evtype=0, code=0, value=0)[source]

This structure is the collection of data for the general event interface. You can create one to write to an event device. If you read from the event device using a subclass of the EventDevice object you will get one of these.

class pycopia.OS.Linux.Input.EventFile(fname, mode='r')[source]

Read from a file containing raw recorded events.

read(amt=None)[source]

Read a single Event object from stream.

class pycopia.OS.Linux.Input.Features(bits=0)[source]

Contains a set of base features. May be actual set as returned by a feature request, or a desired set to find.

pycopia.OS.Linux.Input.get_device_names(start=0)[source]

Returns a list of tuples containing (index, devicename).

SunOS

Process info

Procfs for SunOS.

class pycopia.OS.SunOS.procfs.ProcStat(pid=None)[source]

Status information about a process.

cmdline

Command line

class pycopia.OS.SunOS.procfs.ProcStatTable(fmt='%(pid)6s %(ppid)6s %(ttyname)6.6s %(cmdline).55s')[source]

ProcStatTable() A collection of all processes running, like the standard ‘ps’ command.

FreeBSD

Process and device info

Procfs for FreeBSD.

class pycopia.OS.FreeBSD.procfs.ProcStat(pid=None)[source]

Status information about a process.

cmdline

Command line

class pycopia.OS.FreeBSD.procfs.ProcStatTable(fmt='%(pid)6s %(ppid)6s %(ttyname)6.6s %(cmdline).55s')[source]

ProcStatTable() A collection of all processes running, like the standard ‘ps’ command.