Pycopia Python aid package

These are modules containing objects that are widely useful, or extend core Python features. Some are forks of Python standard library modules that work better on Linux or integrate better with the rest of Pycopia.

Collection of general purpose functions and objects that might be considered general enough to be new built-ins.

class pycopia.aid.Enum[source]

A named number. Behaves as an integer, but produces a name when stringified.

class pycopia.aid.Enums(*init, **kwinit)[source]

A list of Enum objects.


Find the Enum with the given value.


Returns the Enum object given a name string.


Returns the enumerations as a dictionary with naems as keys.

pycopia.aid.IF(test, tv, fv=None)[source]

Functional ‘if’ test. Deprecated, use new Python conditional instead.


Improved __import__ function that returns fully initialized subpackages.

class pycopia.aid.NULL
class pycopia.aid.NULLType(name, bases, dct)[source]

Similar to None, but is also a no-op callable and empty iterable.


Print is a replacement for the built-in print statement. Except that it is a function object.


Printerr writes to stderr.

class pycopia.aid.Queue[source]
class pycopia.aid.Stack[source]
pycopia.aid.add2builtin(name, obj)[source]

Add an object to the builtins namespace.

pycopia.aid.add_exception(excclass, name=None)[source]

Add an exception to the builtins namespace.


Decorator for making methods enter the debugger on an exception.


Generates an indexed series: (0, collection[0]), (1, collection[1]), ...


Flatten a nested set of lists into one list.

class pycopia.aid.formatstr(initstr, **kwargs)[source]

A string with format-style substitutions (limited to the form {name}) with attribute style setters, and inspection of defined substitutions (attributes).

>>> fms = formatstr("This is a {value}.")
>>> fms.value = "somevalue"
>>> print (fms)
>>> fms.value = "othervalue"
>>> print (fms)
pycopia.aid.frange(limit1, limit2=None, increment=1.0)[source]

Range function that accepts floats (and integers).

>>> frange(-2, 2, 0.1)
>>> frange(10)
>>> frange(10, increment=0.5)

The returned value is an iterator. Use list(frange(...)) for a list.


Convert string to string of hexadecimal string for each character.

class pycopia.aid.mapstr(initstr, **kwargs)[source]
pycopia.aid.newclass(name, *bases, **attribs)[source]

Returns a new class with given name, bases and class attributes.

pycopia.aid.pprint_list(thelist[, indent[, width]])[source]

Prints the elements of a list to the screen fitting the most elements per line. Should not break an element across lines. Sort of like word wrap for lists.


Return a list of the elements in s, but without duplicates. Thanks to Tim Peters for fast method.

pycopia.aid.reorder(datalist, indexlist)[source]

Returns a new list that is ordered according to the indexes in the indexlist. e.g. reorder([“a”, “b”, “c”], [2, 0, 1]) -> [“c”, “a”, “b”]

pycopia.aid.repeat(self, n, f)[source]

Call function f, n times.


flush() -> None. Flush the internal I/O buffer.

write(str) -> None. Write string str to file.

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.


Sign function. Returns -1 if val negative, 0 if zero, and 1 if positive.


flush() -> None. Flush the internal I/O buffer.

class pycopia.aid.sortedlist[source]

A list that maintains a sorted order when appended to.


write(str) -> None. Write string str to file.

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.


Convert string to hex-encoded string.


Decorator to make system call methods safe from EINTR.


Take a string of hexadecimal numbers (as ascii) and convert to binary string.

class pycopia.aid.unsigned(val)[source]

Emulate an unsigned 32 bit integer with a long.

bits = 32
ceiling = 4294967295
floor = 0
class pycopia.aid.unsigned64(val)[source]

Emulate an unsigned 64-bit integer.

bits = 64
ceiling = 18446744073709551615L
floor = 0

Special getopt function. It returns long options as a dictionary. Any name-value pair may be given on the command line.

pycopia.getopt.getopt(args, options) → opts, long_opts, args[source]

Returns options as list of tuples, long options as entries in a dictionary, and the remaining arguments.

Functions that read and write gzipped streams.

The user of the file doesn’t have to worry about the compression, but random access is not allowed.

Based on the standard gzip module. That module requires a seekable file. This module buffers data and is useful for decompressing streams.

This module can also handle multiple segments.

Useful for sockets. supports reading only.

TODO: writing has not been tested.

class pycopia.ifconfig.IfConfig[source]

Access to socket interfaces


Get the inet addr for an interface


Get the broadcast addr for an interface


Get the flags for an interface


Get all interface names in a list


Get the netmask for an interface


Check whether interface ‘ifname’ is UP


Return my primary IP address.

Useful terminal/curses related objects. Use this instead of the stock ‘tty’ module, as this module subsumes that functionality.

class pycopia.tty.PagedIO(pagerprompt=None)[source]

PagedIO([pagerprompt]) Reads and writes to stdin/stdout while paging output. automatically adjusts output according to screen size.

class pycopia.tty.SafeSerialPort(fname, mode='w+b', setup='9600 8N1')[source]

A serial port interface protected from interrupted system calls.

class pycopia.tty.SerialPort(fname, mode='w+b', setup='9600 8N1')[source]

Interface to serial/tty ports. This class is not protected from interrupted system calls.


Return number of bytes in input queue.


Quick and easy way to setup the serial port. Supply a string such as “9600 8N1”.


Return a tuple of (row, col, xpixel, ypixel) when the file descriptor (or file object) is a terminal.

pycopia.tty.noecho(fd, when=0)[source]

turn off echo (for slave pty’s)

pycopia.tty.setcbreak(fd, when=2)[source]

Put tty into a cbreak mode.

pycopia.tty.setraw(fd, when=2)[source]

Put tty into a raw mode.

pycopia.tty.slavepty(fd, when=0)[source]

set a pty as ssh does.

pycopia.tty.stty(fd[, flags...])[source]

Stty gets or sets the termios flags for the specified file descriptor. If no argument is given a report is returned as a string. If a flag string is given in the form “flag” or “-flag” then the flag is set, or reset, respectively. Multiple flags of this form may be supplied.

pycopia.tty.terminal_lines(data, cols=80)[source]

Returns the number of lines of a terminal with ‘cols’ columns that the string will consume.

Method introspection.

class pycopia.methods.MethodSignature(method)[source]

Introspect a method or function and store the formal arguments.


:name:      the name of the original function or method.
:arguments: a list of 2-tuples, (argument name, default value). If
            there is no default value defined the value will be NULL object.
get_keyword_arguments(args=(), kwargs=None)[source]

Return a dict with arguments filled in.


Improved __import__ function that returns fully initialized subpackages.

exception pycopia.module.ModuleImportError[source]

Raised when a test module could not be located.

exception pycopia.module.ObjectImportError[source]

Raised when a test object could not be located.

pycopia.module.find_module(modname, path=None)[source]

Find a module, also handling subpackages. Similar to imp.find_module(), except works with subpackages. This does not load the module, so no side effects from the module. It does load the package, so any contents of are run and may have side effects.

fo – Open file object. fname – file name of the file found desc – a 3-tuple of extension, mode, and file type.
pycopia.module.find_package(packagename, searchpath=None)[source]

Find a package by fully qualified name.


Get a class object.

Return a class object from a string specifiying the full package and name path.


Use the Python import function to get a Python package module by name. Raises ModuleImportError if the module could not be found.

name: A string. The name of the module to import and run.
A python module.

Get an object from a Python module, or a module itself.

Python path name of object. Usually a module or a class in a module.
An object identified by the given path name. may raise AttributeError or ModuleImportError if name not found.

Return a list of objects.

A list of object names, as strings.
A tuple of two lists. First list contains object instances corresponding to the given names. May be shorter than the provided list due to objects not being found. Second list is list of errors for names that could not be produced.

Detailed platform detection functions. Differentiate Linux distributions and MS Windows frameworks.

This module provides socket operations and some related functions. On Unix, it supports IP (Internet Protocol) and Unix domain sockets. On other systems, it only supports IP. Functions specific for a socket are available as methods of the socket object.


socket() – create a new socket object socketpair() – create a pair of new socket objects [*] fromfd() – create a socket object from an open file descriptor [*] gethostname() – return the current hostname gethostbyname() – map a hostname to its IP number gethostbyaddr() – map an IP number or hostname to DNS info getservbyname() – map a service name and a protocol name to a port number getprotobyname() – map a protocol name (e.g. ‘tcp’) to a number ntohs(), ntohl() – convert 16, 32 bit int from network to host byte order htons(), htonl() – convert 16, 32 bit int from host to network byte order inet_aton() – convert IP addr string ( to 32-bit packed format inet_ntoa() – convert 32-bit packed format IP to string ( socket.getdefaulttimeout() – get the default timeout value socket.setdefaulttimeout() – set the default timeout value create_connection() – connects to an address, with an optional timeout and optional source address.

[*] not available on all platforms!

Special objects:

SocketType – type object for socket objects error – exception raised for I/O errors has_ipv6 – boolean value indicating if IPv6 is supported

Integer constants:

AF_INET, AF_UNIX – socket domains (first argument to socket() call) SOCK_STREAM, SOCK_DGRAM, SOCK_RAW – socket types (second argument)

Many other constants may be defined; these may be used in calls to the setsockopt() and getsockopt() methods.

class pycopia.socket.socket(family=2, type=1, proto=0, fileno=None)[source]

A subclass of _socket.socket adding the makefile() method.

makefile(...) → an I/O stream connected to the socket[source]

The arguments are as for after the filename,

class pycopia.socket.SocketIO(sock, mode)[source]

Raw I/O implementation for stream sockets.

This class supports the makefile() method on sockets. It provides the raw I/O interface on top of a socket object.


Close the SocketIO object. This doesn’t close the underlying socket, except if all references to it have disappeared.


Return the file descriptor of the underlying socket.


True if the SocketIO is open for reading.


Read up to len(b) bytes into the writable buffer b and return the number of bytes read. If the socket is non-blocking and no bytes are available, None is returned.

If b is non-empty, a 0 return value indicates that the connection was shutdown at the other end.


True if the SocketIO is open for writing.


Write the given bytes or bytearray object b to the socket and return the number of bytes written. This can be less than len(b) if not all data could be written. If the socket is non-blocking and no bytes could be written None is returned.

class pycopia.socket.SafeSocket(family=2, type=1, proto=0, fileno=None)[source]

A socket protected from interrupted system calls.

bind(*args, **kwargs)
connect(*args, **kwargs)
listen(*args, **kwargs)
recv(*args, **kwargs)
send(*args, **kwargs)
sendall(*args, **kwargs)
class pycopia.socket.AsyncSocket(family, type, proto=0)[source]

Socket with the asyncio modules’s async interface.

error_handler(ex, val, tb)[source]
recv(amt, flags=0)[source]
send(data, flags=0)[source]

Get fully qualified domain name from name.

An empty argument is interpreted as meaning the local host.

First the hostname returned by gethostbyaddr() is checked, then possibly existing aliases. In case no FQDN is available, hostname from gethostname() is returned.

pycopia.socket.create_connection(address, timeout=<object object at 0x55ba5c0>, source_address=None)[source]

Connect to address and return the socket object.

Convenience function. Connect to address (a 2-tuple (host, port)) and return the socket object. Passing the optional timeout parameter will set the timeout on the socket instance before attempting to connect. If no timeout is supplied, the global default timeout setting returned by getdefaulttimeout() is used. If source_address is set it must be a tuple of (host, port) for the socket to bind as a source address before making the connection. An host of ‘’ or port 0 tells the OS to use the default.

pycopia.socket.opentcp(host, port, sobject=<class 'pycopia.socket.SafeSocket'>)[source]
pycopia.socket.connect_inet(host, port, socktype, sobject=<class 'pycopia.socket.SafeSocket'>)[source]

General client connections.

pycopia.socket.connect_tcp(host, port, sobject=<class 'pycopia.socket.SafeSocket'>)[source]

Make a TCP client connection.

pycopia.socket.connect_udp(host, port, sobject=<class 'pycopia.socket.SafeSocket'>)[source]

Make a UDP client connection.

pycopia.socket.connect_unix(path, sobject=<class 'pycopia.socket.SafeSocket'>)[source]

Make a Unix socket stream client connection.

pycopia.socket.connect_unix_datagram(path, sobject=<class 'pycopia.socket.SafeSocket'>)[source]
pycopia.socket.unix_listener(path, num=5, sobject=<class 'pycopia.socket.SafeSocket'>)[source]
pycopia.socket.unix_listener_datagram(path, num=5, sobject=<class 'pycopia.socket.SafeSocket'>)[source]
pycopia.socket.udp_listener(addr, num=5, sobject=<class 'pycopia.socket.SafeSocket'>)[source]

return a bound UDP socket.

pycopia.socket.tcp_listener(addr, num=5, sobject=<class 'pycopia.socket.SafeSocket'>)[source]

return a TCP socket, bound and listening.

pycopia.socket.check_port(host, port)[source]

Checks a TCP port on a remote host for a listener. Returns true if a connection is possible, false otherwise.


islocal(host) tests if the given host is ourself, or not.


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


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


alias of socket

exception pycopia.socket.error
pycopia.socket.fromfd(fd, family, type[, proto]) → socket object

Create a socket object from a duplicate of the given file descriptor. The remaining arguments are the same as for socket().

exception pycopia.socket.gaierror
pycopia.socket.getaddrinfo(host, port[, family, socktype, proto, flags])

-> list of (family, socktype, proto, canonname, sockaddr)

Resolve host and port into addrinfo struct.

pycopia.socket.getdefaulttimeout() → timeout

Returns the default timeout in seconds (float) for new socket objects. A value of None indicates that new socket objects have no timeout. When the socket module is first imported, the default is None.

pycopia.socket.gethostbyaddr(host) -> (name, aliaslist, addresslist)

Return the true host name, a list of aliases, and a list of IP addresses, for a host. The host argument is a string giving a host name or IP number.

pycopia.socket.gethostbyname(host) → address

Return the IP address (a string of the form ‘’) for a host.

pycopia.socket.gethostbyname_ex(host) -> (name, aliaslist, addresslist)

Return the true host name, a list of aliases, and a list of IP addresses, for a host. The host argument is a string giving a host name or IP number.

pycopia.socket.gethostname() → string

Return the current host name.

pycopia.socket.getnameinfo(sockaddr, flags) --> (host, port)

Get host and port for a sockaddr.

pycopia.socket.getprotobyname(name) → integer

Return the protocol number for the named protocol. (Rarely used.)

pycopia.socket.getservbyname(servicename[, protocolname]) → integer

Return a port number from a service name and protocol name. The optional protocol name, if given, should be ‘tcp’ or ‘udp’, otherwise any protocol will match.

pycopia.socket.getservbyport(port[, protocolname]) → string

Return the service name from a port number and protocol name. The optional protocol name, if given, should be ‘tcp’ or ‘udp’, otherwise any protocol will match.

exception pycopia.socket.herror
pycopia.socket.htonl(integer) → integer

Convert a 32-bit integer from host to network byte order.

pycopia.socket.htons(integer) → integer

Convert a 16-bit integer from host to network byte order.

pycopia.socket.inet_aton(string) → packed 32-bit IP representation

Convert an IP address in string format ( to the 32-bit packed binary format used in low-level network functions.

pycopia.socket.inet_ntoa(packed_ip) → ip_address_string

Convert an IP address from 32-bit packed binary format to string format

pycopia.socket.inet_ntop(af, packed_ip) → string formatted IP address

Convert a packed IP address of the given family to string format.

pycopia.socket.inet_pton(af, ip) → packed IP address string

Convert an IP address from string format to a packed string suitable for use with low-level network functions.

pycopia.socket.ntohl(integer) → integer

Convert a 32-bit integer from network to host byte order.

pycopia.socket.ntohs(integer) → integer

Convert a 16-bit integer from network to host byte order.


Set the default timeout in seconds (float) for new socket objects. A value of None indicates that new socket objects have no timeout. When the socket module is first imported, the default is None.

class pycopia.socket.socket(family=2, type=1, proto=0, fileno=None)[source]

A subclass of _socket.socket adding the makefile() method.

makefile(...) → an I/O stream connected to the socket[source]

The arguments are as for after the filename,

pycopia.socket.socketpair([family[, type[, proto]]]) -> (socket object, socket object)[source]

Create a pair of socket objects from the sockets returned by the platform socketpair() function. The arguments are the same as for socket() except the default family is AF_UNIX if defined on the platform; otherwise, the default is AF_INET.

exception pycopia.socket.timeout

General text functions. You may import this instead of the stock “string” module in most cases.[source]

Combines all objects lines into one list.


Returns the crc32 value of arguments.

pycopia.textutils.comm(obj1, obj2)[source]
pycopia.textutils.crange(start, fin)[source]

like range(), but for characters.

pycopia.textutils.cut(obj, bytes=None, chars=None, fields=None, delim=" ")[source]

Cut a section from the list of lines. arguments are tuples, except delim.

pycopia.textutils.cut_string(s, maxlen=800)[source]

Cuts a long string, returning the head and tail combined, with the middle missing.

pycopia.textutils.grep(pattern, objects...)[source]

returns a list of matches given an object, which should usually be a list of strings, but could be a single string.


Returns the top 10 lines of the combined objects.


return a hexadecimal string representation of argument lines.


Return a valid Python identifier given an arbitrary string.


Return a valid Python keyword identifier given an arbitrary string.

pycopia.textutils.maketrans(frm, to) → string[source]

Return a translation table (a string of 256 bytes long).


Return the MD5 sum of the arguments.*args)[source]

line numbers - prepends line numbers to strings in list.


Return a string of length <size> with random alphanumeric characters in it.


Return the SHA1 sum of the arguments.

pycopia.textutils.snip_string(s, maxlen=800)

Cuts a long string, returning the head and tail combined, with the middle missing.


sort - Returns argument list sorted.


Combines all objects lines into one list and returns them in reverse order.


Returns the bottom 10 lines of the combined objects.

pycopia.textutils.text(object, ...)[source]

Returns all given objects as a single string.

pycopia.textutils.translate(string, frm, to, table=None, deletechars=None)[source]

Translate a string using table (one will be built if not supplied). First remove ‘deletechars’ characters from ‘string’, then translate the ‘from’ characters to the ‘to’ characters.


Unique - returns the unique elements of the objects.


Word count - returns a tuple of (lines, words, characters) of the objects.


Return tuple of hours, minutes, and seconds given value in seconds.

pycopia.timelib.localtimestamp(secs=None, fmt='%a, %d %b %Y %H:%M:%S %Z')[source]

Return string with , according to given format. Default is rfc822 compliant date value.

pycopia.timelib.seconds(seconds=0, minutes=0, hours=0, days=0, weeks=0)[source]

Returns a value in seconds given some minutes, hours, days, or weeks.

pycopia.timelib.strptime_localtimestamp(ts, fmt='%a, %d %b %Y %H:%M:%S %Z')[source]

Return seconds given a local timestamp string (inverse of localtimestamp function).

pycopia.timelib.timestamp(secs=None, fmt='%a, %d %b %Y %H:%M:%S +0000')[source]

Return string with current time, according to given format. Default is rfc822 compliant date value.


Returns a date that is the Monday of the week specified in universal seconds.


A generator function for generating periods of time.

timespecs (string) a string specifying a sequence of relative time values, separated by commas. Relative time values are of the form “1d” (for one day), “30s” (for thirty seconds), etc. If a substring ”...” is present (it should be last) then make the last two times a delta time and repeat indefinitly, incrementing the time value by that delta time.
An iterator that yields each time mark given, as seconds (float).
class pycopia.timespec.TimespecParser[source]

Loose time span parser. Convert strings such as “1day 3min” to seconds. The attribute “seconds” holds the updated value, after parsing.

Extends the standard urlparse module with some extra parsing functions. Also provides encoding and generating functions.

Parts copied from the standard urlparse module.

class pycopia.urlparse.UniversalResourceLocator(url=None, strict=True)[source]

A general purpose URL object. Parse and generate URLs. Provided for read-modify-write operations.


Full URL


Return address suitable for a socket.


Fragment part


Return address suitable for a socket.


Host part


Params part


Password part


Path part


Port part


URLQuery object


Scheme part


User part

pycopia.urlparse.quote('abc def') → 'abc%20def'[source]

Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted.

RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists the following reserved characters.

reserved = ”;” | “/” | ”?” | ”:” | “@” | “&” | “=” | “+” |
“$” | ”,”

Each of these characters is reserved in some component of a URL, but not necessarily in all of them.

By default, the quote function is intended for quoting the path section of a URL. Thus, it will not encode ‘/’. This character is reserved, but in typical usage the quote function is being called on a path where the existing slash characters are used as reserved characters.

pycopia.urlparse.quote_plus(s, safe='')[source]

Quote the query fragment of a URL; replacing ‘ ‘ with ‘+’


Parses a server part and returns a 4-tuple (user, password, host, port).

pycopia.urlparse.unquote('abc%20def') → 'abc def'.[source]

unquote(‘%7e/abc+def’) -> ‘~/abc def’

pycopia.urlparse.uriparse(uri, strict=False)[source]

Given a valid URI, return a 5-tuple of (scheme, authority, path, query, fragment). The query part is a URLQuery object, the rest are strings. Raises ValueError if URI is malformed.

pycopia.urlparse.urlencode(query, doseq=0)[source]

Encode a sequence of two-element tuples or dictionary into a URL query string.

If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter.

If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input.

pycopia.urlparse.urlparse(uri, strict=False)

Given a valid URI, return a 5-tuple of (scheme, authority, path, query, fragment). The query part is a URLQuery object, the rest are strings. Raises ValueError if URI is malformed.

class pycopia.UserFile.FileConverter(linesep=None)[source]

Converts text files to and from various platform line ending conventions.

convert(srcname, dstname)[source]
convertfileobject(src, dst)[source]
class pycopia.UserFile.FileWrapper(fo, linesep=None, logfile=None, restart=True)[source]

FileWrapper(fileobject, [logfile]) Wraps a file-like object with safe read methods, and allows logged reads.

class pycopia.UserFile.MergedIO(outf, inf)[source]

MergedIO(outfile, infile) Combines a write stream and a read stream into one read/write object.

class pycopia.UserFile.PipeIO(pipe)[source]

PipeIO(pipefileobject) Reads from and manages the reading from a named pipe. Useful for daemon processes.

class pycopia.UserFile.TextFile(name, mode='r', bufsize=-1, linesep=None)[source]

TextFile(self, name, mode=”r”, bufsize=-1, linesep=None) A file object that handles different line separator conventions. This file object’s readline() method returns the line with trailing line separator stripped, and raises EOFError on end of file. The writelines() method will append an appropriate line separator when writing. Thus, this file object allows reading and writeing non-native text files.

class pycopia.UserFile.UserFile[source]
lock(length=0, start=0, whence=0, nb=0)
lock_exclusive(length=0, start=0, whence=0, nb=0)[source]
lock_shared(length=0, start=0, whence=0, nb=0)[source]
unlock(length=0, start=0, whence=0)[source]
pycopia.UserFile.copyfileobj(src, dst[, bufsize])[source]

copy data from file-like object fsrc to file-like object fdst

pycopia.UserFile.copylines(src, dst)[source]

Copy text lines from file-like object src to TextFile object dst. End-of-line conversion is performed (via the TextFile object).

pycopia.UserFile.dos2mac(srcname, dstname)[source]

Copies a file in DOS text format to Macintosh text format.

pycopia.UserFile.dos2unix(srcname, dstname)[source]

Copies a file in DOS text format to Unix text format.


where fd is an integer file descriptor of an open file. Returns the files open flags as a vertical bar (|) delimited string.

pycopia.UserFile.mac2dos(srcname, dstname)[source]

Copies a file in Macintosh text format to DOS text format.

pycopia.UserFile.mac2unix(srcname, dstname)[source]

Copies a file in Macintosh text format to Unix text format.


Converts a file mode in string form (e.g. “w+”) to an integer flag value suitable for


Get a suitalbe mode string for an fd., mode='r', bufsize=-1)[source]
pycopia.UserFile.open_dosfile(name, mode='r', bufsize=-1)[source]

returns a TextFile with DOS style line endings.

pycopia.UserFile.open_macfile(name, mode='r', bufsize=-1)[source]

returns a TextFile with Macintosh style line endings.

pycopia.UserFile.open_textfile(name, mode='r', bufsize=-1, linesep='unix')[source]

Open a text file of a particular platform flavor. Text lines written to this file with the writeline(s) method will have the appropriate line endings.

pycopia.UserFile.open_unixfile(name, mode='r', bufsize=-1)[source]

returns a TextFile with Unix style line endings.

pycopia.UserFile.unix2dos(srcname, dstname)[source]

Copies a file in unix text format to DOS text format.

pycopia.UserFile.unix2mac(srcname, dstname)[source]

Copies a file in unix text format to Macintosh text format.

pycopia.UserFile.writelines(filename, lines, texttype="unix")[source]

Make a file of a particular text type, given a list of lines (without line endings), and a file name.

fetch words from the system word list, using regular expressions.


Return a randomly selected word from dict file.

pycopia.words.get_word_list(patt, wordfile=None)[source]

Yield words matching pattern (like grep).

Helpers and tools for dictionary objects. Various useful dictionary variants live here.

class pycopia.dictlib.AttrDict(*args, **kwargs)[source]

A dictionary with attribute-style access. It maps attribute access to the real dictionary.

class pycopia.dictlib.AttrDictDefault(init={}, default=None)[source]

A dictionary with attribute-style access. It maps attribute access to the real dictionary. Returns a default entry if key is not found.

class pycopia.dictlib.AttrDictWrapper(mapping=None)[source]

Wraps any mapping object with the ability to get to its contents using attribute access syntax (dot). Note that you cannot have any contained keys that match an attribute name.

class pycopia.dictlib.MultiValueDict(key_to_list_mapping=())[source]

A subclass of dictionary customized to handle multiple values for the same key.

>>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})
>>> d['name']
>>> d.getlist('name')
['Adrian', 'Simon']
>>> d.get('lastname', 'nonexistent')
>>> d.setlist('lastname', ['Holovaty', 'Willison'])

This class exists to solve the irritating problem raised by cgi.parse_qs, which returns a list for every key, even though most Web forms submit single name-value pairs.

appendlist(key, value)[source]

Appends an item to the internal list associated with key


Returns a copy of this object.

get(key, default=None)[source]

Returns the default value if the requested data doesn’t exist


Returns an empty list if the requested data doesn’t exist


Returns a list of (key, value) pairs, where value is the last item in the list associated with the key.


Returns a list of (key, list) pairs.

update(*args, **kwargs)[source]

update() extends rather than replaces existing key lists. Also accepts keyword args.


Returns a list of the last value on every key list.

class pycopia.dictlib.ObjectCache[source]

A dict that caches objects. Adds a method, get_object, that works like get() but takes a constructor callable that is called if the object is not found here.

class pycopia.dictlib.SortedDict(data=None)[source]

A dictionary that keeps its keys in the order in which they’re inserted.


Returns the value of the item at the given zero-based index.

Previous topic

Installing on Redhat 6.x

Next topic

Pycopia utils package