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]
exception_handler(ex, val, tb)[source]
class pycopia.asyncio.AsyncIOHandler(fo)[source]
exception_handler(ex, val, tb)[source]
class pycopia.asyncio.AsyncServerHandler(sock, workerclass)[source]
class pycopia.asyncio.AsyncWorkerHandler(sock, addr)[source]
exception_handler(ex, val, tb)[source]

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


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

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.

exception_handler(ex, val, tb)[source]
loop(timeout=-1.0, callback=NULL)[source]
register_fd(fd, flags, callback)[source]
class pycopia.asyncio.PollerInterface[source]
exception_handler(ex, val, tb)[source]
class pycopia.asyncio.SIGIOHandler[source]
register(callback, *args)[source]

Sets io object to use SIGIO.

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! )


factorial(x) return x!


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.


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


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


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]

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


Opens the given search term with a CHM viewer.


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)

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


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.


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.


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.


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.


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.


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()).


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.


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.


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


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]
class pycopia.ipv4.IPv4(address, mask=None)[source]

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


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("")
ip = IPv4("", "")
ip = IPv4("") # 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.


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.


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("", "")
    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

Returns string in CIDR notation.


whole address


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


Returns string in CIDR notation.


first host in range


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


Resolve this IP address to a canonical name using gethostbyaddr.


host part


associated host name


host part


last host in range


address mask


CIDR mask bits


network part


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.


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.


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.


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 the address to the first host in the network.


Set the address to the last host in the network.


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.

ipnetrange(startnet, number, [increment])
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.

iprange(startip, number)
startip is an IP address to start from. number is the number of IP addresses in the returned list.

Return a dotted-quad string given an integer.


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.

netrange(startnet, number, [increment])
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.


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.

pycopia.jsonconfig.dump(conf, fo)[source]
pycopia.jsonconfig.get_config(filename=None, init=None)[source]

Get an existing or new json config object.

Optionally initialize from another dictionary.


Read a JSON config file.

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.


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

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.

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

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


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


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.


Method name

Implements a netstring object, as described in:

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.


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'

Fill this in with state transitions.

run(iostream, data=None)[source]
step(iostream, data=None)[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]
set_default_transition(action, next_state)[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]
exception pycopia.re_inverse.UnhandledOpError[source]
pycopia.re_inverse.compile(regexp, flags=0)[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.


I shared memory object for IPC support using coprocesses.

A parser for splitting a simple POSIX shell syntax.

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

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

VARNAME = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_?'
interact(ps1='shparse> ', ps2='more> ')[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.


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.


Closes the server (stops listening).


Fetches the conversation list-object from this server.


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.


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]
is a file object for the template file. This file contains unique strings that must match the keys in the subsititution dictionary (sustitutedict).
is a file object that will have the template file with substitutions written to it.
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.


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


  • 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’.

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.


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.

usespace(space=u' ')[source]
class pycopia.physics.physical_quantities.PhysicalUnit(names, factor, powers, offset=0)[source]

Returns 1 if x is an instance of PhysicalQuantity.


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.


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).


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


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


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.


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.


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


Optional. The HttpOnly attribute.


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.


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


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.


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: <> default value: “Mozilla/5.0 (X11; U; Linux i686; en-US)”


Factory for getting proper header object from text line.


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 <>.

For more information about the Web Server Gateway Interface, see <>.

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 <>.

The FastCGI server.

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


Handles WSGI request.


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.


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.


Yield unfolded lines from a chunk of text.


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.


Adds a new recipient to the RCPT list.


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


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.


Sets the MAIL FROM address for this Envelope.


Writes text to the message body.


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:

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

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

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

    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

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 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.


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.


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


SMTP ‘verify’ command – checks for address validity.


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.


Does the server support a given SMTP service extension?


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


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
mail(sender, options=[])[source]

SMTP ‘mail’ command – begins mail xfer session.


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

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

Send a command to the server.


Terminate the SMTP session.

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

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


SMTP ‘rset’ command – resets session.


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.


>>> import smtplib
>>> s=smtplib.SMTP("localhost")
>>> tolist=["","","",""]
>>> msg = '''\
... From:
... Subject: testin'...
... This is a test '''
>>> s.sendmail("",tolist,msg)
{ "" : ( 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.


SMTP ‘verify’ command – checks for address validity.


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.


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


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 /proc data

The devices file.

Interface to the /proc/interrupts file.

Interface to the /proc/mounts file.

Read /proc/net/dev data.



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, 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.


Represents the kernel FIB. Supports sequence operators.


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.


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

Devices 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() Returns and rtc_time object. Note that only the hour, minute, and second fields are used.


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


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


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() Returns an rtc_time object. Note that the RTC driver only fills in the year, month, day, hour, minute, and second fields.


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


Turn off update interrupts (one per second)


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 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.


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


Process info

Procfs for SunOS.

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

Status information about a process.


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.


Process and device info

Procfs for FreeBSD.

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

Status information about a process.


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.