100% found this document useful (6 votes)
31 views72 pages

Python Standard Library Fredrik Lundh Download PDF

Standard

Uploaded by

iyusmorra4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
31 views72 pages

Python Standard Library Fredrik Lundh Download PDF

Standard

Uploaded by

iyusmorra4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 72

Download the full version of the ebook now at ebookultra.

com

Python Standard Library Fredrik Lundh

https://ebookultra.com/download/python-standard-
library-fredrik-lundh/

Explore and download more ebook at https://ebookultra.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

The Python Standard Library by Example 1st Edition


Hellmann

https://ebookultra.com/download/the-python-standard-library-by-
example-1st-edition-hellmann/

ebookultra.com

The C Standard Library 2nd Edition Nicolai M. Josuttis

https://ebookultra.com/download/the-c-standard-library-2nd-edition-
nicolai-m-josuttis/

ebookultra.com

The Standard ML Basis Library 1st Edition Emden R. Gansner

https://ebookultra.com/download/the-standard-ml-basis-library-1st-
edition-emden-r-gansner/

ebookultra.com

Core JSTL Mastering the JSP Standard Tag Library 1st


Edition Geary

https://ebookultra.com/download/core-jstl-mastering-the-jsp-standard-
tag-library-1st-edition-geary/

ebookultra.com
One Discipline Four Ways Fredrik Barth

https://ebookultra.com/download/one-discipline-four-ways-fredrik-
barth/

ebookultra.com

We Are All Leaders 1st Edition Fredrik Arnander

https://ebookultra.com/download/we-are-all-leaders-1st-edition-
fredrik-arnander/

ebookultra.com

Us Against You Beartown 2 1st Edition Fredrik Backman

https://ebookultra.com/download/us-against-you-beartown-2-1st-edition-
fredrik-backman/

ebookultra.com

STL Tutorial and Reference Guide C Programming With the


Standard Template Library 2 (Draft) Edition David R.
Musser
https://ebookultra.com/download/stl-tutorial-and-reference-guide-c-
programming-with-the-standard-template-library-2-draft-edition-david-
r-musser/
ebookultra.com

Bioreactors design operation and novel applications 1st


Edition Carl-Fredrik Mandenius

https://ebookultra.com/download/bioreactors-design-operation-and-
novel-applications-1st-edition-carl-fredrik-mandenius/

ebookultra.com
Python Standard Library Fredrik Lundh Digital Instant
Download
Author(s): Fredrik Lundh
ISBN(s): 9780596000967, 0596000960
Edition: Kindle
File Details: PDF, 1.81 MB
Year: 2001
Language: english
Preface
"We'd like to pretend that "Fredrik" is a role, but even hundreds of
volunteers couldn't possibly keep up. No, "Fredrik" is the result of
crossing an http server with a spam filter with an emacs whatsit and
some other stuff besides"

Gordon McMillan, June 1998

The Python 2.0 distribution comes with an extensive standard library, comprising over 200 modules.
This book provides a brief description of each module, plus one or more sample scripts showing how to
use it. All in all, this book contains 360 sample scripts.

About this Book


"Those people who have nothing better to do than post on the Internet
all day long are rarely the ones who have the most insights"

Jacob Nielsen, December 1998

Since I first stumbled upon Python some five years ago, I've spent hundreds of hours answering
questions on the comp.lang.python newsgroup. Maybe someone found a module that might be
exactly what he wanted, but he couldn't really figure out how to use it. Maybe someone had picked the
wrong module for the task. Or maybe someone tried to reinvent the wheel. Often, a short sample script
could be much more helpful than a pointer to the reference documentation.
After posting a couple of scripts each week, for a number of years, you end up with a rather large
collection of potentially useful scripts. What you'll find in this book are the best parts from over 3,000
newsgroup messages. You'll also find hundreds of new scripts added to make sure every little nook and
cranny of the standard library has been fully covered.
I've worked hard to make the scripts easy to understand and adaptable. I've intentionally kept the
annotations as short as possible. If you want more background, there's plenty of reference material
shipped with most Python distributions. In this book, the emphasis is on the code.
Comments, suggestions, and bug reports are welcome. Send them to [email protected]. I read
all mail as soon as it arrives, but it might take a while until I get around to answer.
For updates, addenda, and other information related to this book, point your favorite web browser to
http://www.pythonware.com/people/fredrik/librarybook.htm

Python Standard Library


Copyright (c) 1999-2003 by Fredrik Lundh. All rights reserved.
What about Tkinter?

This book covers the entire standard library, except the (optional) Tkinter user interface library. There
are several reasons for this, mostly related to time, space, and the fact that I'm working on several
other Tkinter documentation projects.
For current status on these projects, see http://www.pythonware.com/people/fredrik/tkinterbook.htm

Production details

This book was written in DocBook SGML. I used a variety of tools, including Secret Labs'
PythonWorks, and Excosoft Documentor, James Clark's Jade DSSSL processor, and Norm Walsh's
DocBook stylesheets. And a bunch of Python scripts, of course.
Thanks to my referees: Tim Peters, Guido van Rossum, David Ascher, Mark Lutz, and Rael Dornfest,
and the PythonWare crew: Matthew Ellis, Håkan Karlsson, and Rune Uhlin.
Thanks to Lenny Muellner, who turned my SGML files into the book you see before you, and to
Christien Shanreaw, who pulled all the different text and code files together for the book and the CD-
ROM.

About the Examples


Unless otherwise noted, all examples run under Python 1.5.2 and Python 2.0. I've tried not to depend
on internal details, and I expect most scripts to work with upcoming 2.x versions as well.
The examples have been tested on Windows, Solaris, and Linux. Except for a few scripts that depend
on platform specific modules, the examples should work right out of the box on most other platforms
as well. (If you find something that doesn't work as expected, let me know!)
All code is copyrighted. Of course, you're free to use one or more modules in your own programs, just
don't forget where you got them.
Most script files are named after the module they're using, followed by the string "-example-" and a
unique "serial number". Note that the scripts sometimes appear out of order; it's done this way on
purpose, to match the filenames used in an earlier version of this book, (the eff-bot guide to) The
Standard Python Library.
You'll find copies of all scripts on the CD provided with this book. For updates and more information,
see http://www.pythonware.com/people/fredrik/librarybook.htm.
Python Standard Library: Core Modules 1-1

Core Modules
"Since the functions in the C runtime library are not part of the Win32
API, we believe the number of applications that will be affected by this
bug to be very limited"

Microsoft, January 1999

Overview
Python's standard library covers a wide range of modules. Everything from modules that are as much a
part of the Python language as the types and statements defined by the language specification, to
obscure modules that are probably useful only to a small number of programs.
This section describes a number of fundamental standard library modules. Any larger Python program
is likely to use most of these modules, either directly or indirectly.

Built-in Functions and Exceptions

Two modules are even more basic than all other modules combined: the __builtin__ module defines
built-in functions (like len, int, and range), and the exceptions module defines all built-in
exceptions.
Python imports both modules when it starts up, and makes their content available for all programs.

Operating System Interface Modules


There are a number of modules providing platform-independent interfaces to the underlying operating
system. They are modeled after the POSIX standard API and the standard C library.
The modules in this group include os, which provides file and process operations, os.path which
offers a platform-independent way to pull apart and put together file names, and time which provides
functions to work with dates and times.
To some extent, networking and thread support modules could also belong in this group, but they are
not supported by all Python implementations.

Python Standard Library


Copyright (c) 1999-2003 by Fredrik Lundh. All rights reserved.
Python Standard Library: Core Modules 1-2

Type Support Modules

Several built-in types have support modules in the standard library. The string module implements
commonly used string operations, the math module provides math operations and constants, and the
cmath module does the same for complex numbers.

Regular Expressions

The re module provides regular expressions support for Python. Regular expressions are string
patterns written in a special syntax, which can be used to match strings, and extract substrings.

Language Support Modules

sys gives you access to various interpreter variables, such as the module search path, and the
interpreter version. operator provides functional equivalents to many built-in operators. copy allows
you to copy objects. And finally, gc gives you more control over the garbage collector facilities in
Python 2.0.
Python Standard Library: Core Modules 1-3

The __builtin__ module


This module contains built-in functions which are automatically available in all Python modules. You
usually don't have to import this module; Python does that for you when necessary.

Calling a function with arguments from a tuple or dictionary


Python allows you to build function argument lists on the fly. Just put all the arguments in a tuple, and
call the built-in apply function:

Example: Using the apply function


# File:builtin-apply-example-1.py

def function(a, b):


print a, b

apply(function, ("whither", "canada?"))


apply(function, (1, 2 + 3))

whither canada?
15

To pass keyword arguments to a function, you can use a dictionary as the third argument to apply:

Example: Using the apply function to pass keyword arguments


# File:builtin-apply-example-2.py

def function(a, b):


print a, b

apply(function, ("crunchy", "frog"))


apply(function, ("crunchy",), {"b": "frog"})
apply(function, (), {"a": "crunchy", "b": "frog"})

crunchy frog
crunchy frog
crunchy frog
Python Standard Library: Core Modules 1-4

One common use for apply is to pass constructor arguments from a subclass on to the base class,
especially if the constructor takes a lot of arguments.

Example: Using the apply function to call base class constructors


# File:builtin-apply-example-3.py

class Rectangle:
def __init__(self, color="white", width=10, height=10):
print "create a", color, self, "sized", width, "x", height

class RoundedRectangle(Rectangle):
def __init__(self, **kw):
apply(Rectangle.__init__, (self,), kw)

rect = Rectangle(color="green", height=100, width=100)


rect = RoundedRectangle(color="blue", height=20)

create a green <Rectangle instance at 8c8260> sized 100 x 100


create a blue <RoundedRectangle instance at 8c84c0> sized 10 x 20

Python 2.0 provides an alternate syntax. Instead of apply, you can use an ordinary function call, and
use * to mark the tuple, and ** to mark the dictionary.
The following two statements are equivalent:
result = function(*args, **kwargs)
result = apply(function, args, kwargs)

Loading and reloading modules


If you've written a Python program larger than just a few lines, you know that the import statement is
used to import external modules (you can also use the from-import version). What you might not
know already is that import delegates the actual work to a built-in function called __import__.
Python Standard Library: Core Modules 1-5

The trick is that you can actually call this function directly. This can be handy if you have the module
name in a string variable, like in the following example, which imports all modules whose names end
with "-plugin":

Example: Using the __import__ function to load named modules


# File:builtin-import-example-1.py

import glob, os

modules = []

for module_file in glob.glob("*-plugin.py"):


try:
module_name, ext = os.path.splitext(os.path.basename(module_file))
module = __import__(module_name)
modules.append(module)
except ImportError:
pass # ignore broken modules

# say hello to all modules


for module in modules:
module.hello()

example-plugin says hello

Note that the plugin modules have hyphens in the name. This means that you cannot import such a
module using the ordinary import command, since you cannot have hyphens in Python identifiers.
Here's the plugin used in this example:

Example: A sample plugin


# File:example-plugin.py

def hello():
print "example-plugin says hello"

The following example shows how to get a function object, given that you have the module and
function name as strings:

Example: Using the __import__ function to get a named function


# File:builtin-import-example-2.py

def getfunctionbyname(module_name, function_name):


module = __import__(module_name)
return getattr(module, function_name)

print repr(getfunctionbyname("dumbdbm", "open"))

<function open at 794fa0>


Python Standard Library: Core Modules 1-6

You can also use this function to implement lazy loading of modules. In the following example, the
string module is imported when it is first used:

Example: Using the __import__ function to implement lazy import


# File:builtin-import-example-3.py

class LazyImport:
def __init__(self, module_name):
self.module_name = module_name
self.module = None
def __getattr__(self, name):
if self.module is None:
self.module = __import__(self.module_name)
return getattr(self.module, name)

string = LazyImport("string")

print string.lowercase

abcdefghijklmnopqrstuvwxyz

Python provides some basic support for reloading modules that you've already imported. The following
example loads the hello.py file three times:

Example: Using the reload function


# File:builtin-reload-example-1.py

import hello
reload(hello)
reload(hello)

hello again, and welcome to the show


hello again, and welcome to the show
hello again, and welcome to the show

reload uses the module name associated with the module object, not the variable name. This means
that even if you've renamed the module, reload will still be able to find the original module.
Note that when you reload a module, it is recompiled, and the new module replaces the old one in the
module dictionary. However, if you have created instances of classes defined in that module, those
instances will still use the old implementation.
Likewise, if you've used from-import to create references to module members in other modules,
those references will not be updated.
Python Standard Library: Core Modules 1-7

Looking in namespaces

The dir function returns a list of all members of a given module, class, instance, or other type. It's
probably most useful when you're working with an interactive Python interpreter, but can also come in
handy in other situations.

Example: Using the dir function


# File:builtin-dir-example-1.py

def dump(value):
print value, "=>", dir(value)

import sys

dump(0)
dump(1.0)
dump(0.0j) # complex number
dump([]) # list
dump({}) # dictionary
dump("string")
dump(len) # function
dump(sys) # module

0 => []
1.0 => []
0j => ['conjugate', 'imag', 'real']
[] => ['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
{} => ['clear', 'copy', 'get', 'has_key', 'items',
'keys', 'update', 'values']
string => []
<built-in function len> => ['__doc__', '__name__', '__self__']
<module 'sys' (built-in)> => ['__doc__', '__name__',
'__stderr__', '__stdin__', '__stdout__', 'argv',
'builtin_module_names', 'copyright', 'dllhandle',
'exc_info', 'exc_type', 'exec_prefix', 'executable',
...

In the following example, the getmember function returns all class-level attributes and methods
defined by a given class:

Example: Using the dir function to find all members of a class


# File:builtin-dir-example-2.py

class A:
def a(self):
pass
def b(self):
pass
Python Standard Library: Core Modules 1-8

class B(A):
def c(self):
pass
def d(self):
pass

def getmembers(klass, members=None):


# get a list of all class members, ordered by class
if members is None:
members = []
for k in klass.__bases__:
getmembers(k, members)
for m in dir(klass):
if m not in members:
members.append(m)
return members

print getmembers(A)
print getmembers(B)
print getmembers(IOError)

['__doc__', '__module__', 'a', 'b']


['__doc__', '__module__', 'a', 'b', 'c', 'd']
['__doc__', '__getitem__', '__init__', '__module__', '__str__']

Note that the getmembers function returns an ordered list. The earlier a name appears in the list, the
higher up in the class hierarchy it's defined. If order doesn't matter, you can use a dictionary to collect
the names instead of a list.
The vars function is similar, but it returns a dictionary containing the current value for each member.
If you use it without an argument, it returns a dictionary containing what's visible in the current local
namespace:

Example: Using the vars function


# File:builtin-vars-example-1.py

book = "library2"
pages = 250
scripts = 350

print "the %(book)s book contains more than %(scripts)s scripts" % vars()

the library book contains more than 350 scripts


Python Standard Library: Core Modules 1-9

Checking an object's type

Python is a dynamically typed language, which means that a given variable can be bound to values of
different types at different occasions. In the following example, the same function is called with an
integer, a floating point value, and a string:
def function(value):
print value

function(1)
function(1.0)
function("one")

The type function allows you to check what type a variable has. This function returns a type
descriptor, which is a unique object for each type provided by the Python interpreter.

Example: Using the type function


# File:builtin-type-example-1.py

def dump(value):
print type(value), value

dump(1)
dump(1.0)
dump("one")

<type 'int'> 1
<type 'float'> 1.0
<type 'string'> one

Each type has a single corresponding type object, which means that you can use the is operator (object
identity) to do type testing:

Example: Using the type function to distinguish between file names and file objects
# File:builtin-type-example-2.py

def load(file):
if isinstance(file, type("")):
file = open(file, "rb")
return file.read()

print len(load("samples/sample.jpg")), "bytes"


print len(load(open("samples/sample.jpg", "rb"))), "bytes"

4672 bytes
4672 bytes
Python Standard Library: Core Modules 1-10

The callable function checks if an object can be called (either directly or via apply). It returns true for
functions, methods, lambda expressions, classes, and class instances which define the __call__
method.

Example: Using the callable function


# File:builtin-callable-example-1.py

def dump(function):
if callable(function):
print function, "is callable"
else:
print function, "is *not* callable"

class A:
def method(self, value):
return value

class B(A):
def __call__(self, value):
return value

a = A()
b = B()

dump(0) # simple objects


dump("string")
dump(callable)
dump(dump) # function

dump(A) # classes
dump(B)
dump(B.method)

dump(a) # instances
dump(b)
dump(b.method)

0 is *not* callable
string is *not* callable
<built-in function callable> is callable
<function dump at 8ca320> is callable
A is callable
B is callable
<unbound method A.method> is callable
<A instance at 8caa10> is *not* callable
<B instance at 8cab00> is callable
<method A.method of B instance at 8cab00> is callable

Note that the class objects (A and B) are both callable; if you call them, they create new objects.
However, instances of class A are not callable, since that class doesn't have a __call__ method.
You'll find functions to check if an object is of any of the built-in number, sequence, or dictionary types
in the operator module. However, since it's easy to create a class that implements e.g. the basic
sequence methods, it's usually a bad idea to use explicit type testing on such objects.
Python Standard Library: Core Modules 1-11

Things get even more complicated when it comes to classes and instances. Python doesn't treat classes
as types per se. Instead, all classes belong to a special class type, and all class instances belong to a
special instance type.
This means that you cannot use type to test if an instance belongs to a given class; all instances have
the same type! To solve this, you can use the isinstance function, which checks if an object is an
instance of a given class (or of a subclass to it).

Example: Using the isinstance function


# File:builtin-isinstance-example-1.py

class A:
pass

class B:
pass

class C(A):
pass

class D(A, B):


pass

def dump(object):
print object, "=>",
if isinstance(object, A):
print "A",
if isinstance(object, B):
print "B",
if isinstance(object, C):
print "C",
if isinstance(object, D):
print "D",
print

a = A()
b = B()
c = C()
d = D()

dump(a)
dump(b)
dump(c)
dump(d)
dump(0)
dump("string")

<A instance at 8ca6d0> => A


<B instance at 8ca750> => B
<C instance at 8ca780> => A C
<D instance at 8ca7b0> => A B D
0 =>
string =>
Python Standard Library: Core Modules 1-12

The issubclass function is similar, but checks whether a class object is the same as a given class, or is
a subclass of it.
Note that while isinstance accepts any kind of object, the issubclass function raises a TypeError
exception if you use it on something that is not a class object.

Example: Using the issubclass function


# File:builtin-issubclass-example-1.py

class A:
pass

class B:
pass

class C(A):
pass

class D(A, B):


pass

def dump(object):
print object, "=>",
if issubclass(object, A):
print "A",
if issubclass(object, B):
print "B",
if issubclass(object, C):
print "C",
if issubclass(object, D):
print "D",
print

dump(A)
dump(B)
dump(C)
dump(D)
dump(0)
dump("string")

A => A
B => B
C => A C
D => A B D
0 =>
Traceback (innermost last):
File "builtin-issubclass-example-1.py", line 29, in ?
File "builtin-issubclass-example-1.py", line 15, in dump
TypeError: arguments must be classes
Python Standard Library: Core Modules 1-13

Evaluating Python expressions

Python provides several ways to interact with the interpreter from within a program. For example, the
eval function evaluates a string as if it were a Python expression. You can pass it a literal, simple
expressions, or even use built-in functions:

Example: Using the eval function


# File:builtin-eval-example-1.py

def dump(expression):
result = eval(expression)
print expression, "=>", result, type(result)

dump("1")
dump("1.0")
dump("'string'")
dump("1.0 + 2.0")
dump("'*' * 10")
dump("len('world')")

1 => 1 <type 'int'>


1.0 => 1.0 <type 'float'>
'string' => string <type 'string'>
1.0 + 2.0 => 3.0 <type 'float'>
'*' * 10 => ********** <type 'string'>
len('world') => 5 <type 'int'>

A problem with eval is that if you cannot trust the source from which you got the string, you may get
into trouble. For example, someone might use the built-in __import__ function to load the os
module, and then remove files on your disk:

Example: Using the eval function to execute arbitrary commands


# File:builtin-eval-example-2.py

print eval("__import__('os').getcwd()")
print eval("__import__('os').remove('file')")

/home/fredrik/librarybook
Traceback (innermost last):
File "builtin-eval-example-2", line 2, in ?
File "<string>", line 0, in ?
os.error: (2, 'No such file or directory')

Note that you get an os.error exception, which means that Python actually tried to remove the file!
Python Standard Library: Core Modules 1-14

Luckily, there's a way around this problem. You can pass a second argument to eval, which should
contain a dictionary defining the namespace in which the expression is evaluated. Let's pass in an
empty namespace:

>>> print eval("__import__('os').remove('file')", {})


Traceback (innermost last):
File "<stdin>", line 1, in ?
File "<string>", line 0, in ?
os.error: (2, 'No such file or directory')

Hmm. We still end up with an os.error exception.


The reason for this is that Python looks in the dictionary before it evaluates the code, and if it doesn't
find a variable named __builtins__ in there (note the plural form), it adds one:
>>> namespace = {}
>>> print eval("__import__('os').remove('file')", namespace)
Traceback (innermost last):
File "<stdin>", line 1, in ?
File "<string>", line 0, in ?
os.error: (2, 'No such file or directory')
>>> namespace.keys()
['__builtins__']

If you print the contents of the namespace variable, you'll find that it contains the full set of built-in
functions.
The solution to this little dilemma isn't far away: since Python doesn't add this item if it is already
there, you just have to add a dummy item called __builtins__ to the namespace before calling eval:

Example: Safely using the eval function to evaluate arbitrary strings


# File:builtin-eval-example-3.py

print eval("__import__('os').getcwd()", {})


print eval("__import__('os').remove('file')", {"__builtins__": {}})

/home/fredrik/librarybook
Traceback (innermost last):
File "builtin-eval-example-3.py", line 2, in ?
File "<string>", line 0, in ?
NameError: __import__

Note that this doesn't product you from CPU or memory resource attacks (for example, something like
eval("'*'*1000000*2*2*2*2*2*2*2*2*2") will most likely cause your program to run out of
memory after a while)
Python Standard Library: Core Modules 1-15

Compiling and executing code

The eval function only works for simple expressions. To handle larger blocks of code, use the compile
and exec functions:

Example: Using the compile function to check syntax


# File:builtin-compile-example-1.py

NAME = "script.py"

BODY = """
prnt 'owl-stretching time'
"""

try:
compile(BODY, NAME, "exec")
except SyntaxError, v:
print "syntax error:", v, "in", NAME

syntax error: invalid syntax in script.py

When successful, the compile function returns a code object, which you can execute with the exec
statement:

Example: Compiling and executing compiled code


# File:builtin-compile-example-2.py

BODY = """
print 'the ant, an introduction'
"""

code = compile(BODY, "<script>", "exec")

print code

exec code

<code object ? at 8c6be0, file "<script>", line 0>


the ant, an introduction
Python Standard Library: Core Modules 1-16

To generate code on the fly, you can use the class shown in the following example. Use the write
method to add statements, and indent and dedent to add structure, and this class takes care of the
rest.

Example: A simple code generator tool


# File:builtin-compile-example-3.py

import sys, string

class CodeGeneratorBackend:
"Simple code generator for Python"

def begin(self, tab="\t"):


self.code = []
self.tab = tab
self.level = 0

def end(self):
self.code.append("") # make sure there's a newline at the end
return compile(string.join(self.code, "\n"), "<code>", "exec")

def write(self, string):


self.code.append(self.tab * self.level + string)

def indent(self):
self.level += 1
# in Python 1.5.2 and earlier, use this instead:
# self.level = self.level + 1

def dedent(self):
if self.level == 0:
raise SyntaxError, "internal error in code generator"
self.level -= 1
# in Python 1.5.2 and earlier, use this instead:
# self.level = self.level - 1

#
# try it out!

c = CodeGeneratorBackend()
c.begin()
c.write("for i in range(5):")
c.indent()
c.write("print 'code generation made easy!'")
c.dedent()
exec c.end()

code generation made easy!


code generation made easy!
code generation made easy!
code generation made easy!
code generation made easy!
Python Standard Library: Core Modules 1-17

Python also provides a function called execfile. It's simply a shortcut for loading code from a file,
compiling it, and executing it. The following example shows how to use and emulate this function.

Example: Using the execfile function


# File:builtin-execfile-example-1.py

execfile("hello.py")

def EXECFILE(filename, locals=None, globals=None):


exec compile(open(filename).read(), filename, "exec") in locals, globals

EXECFILE("hello.py")

hello again, and welcome to the show


hello again, and welcome to the show

The hello.py file used in this example has the following contents:

Example: The hello.py script


# File:hello.py

print "hello again, and welcome to the show"

Overloading functions from the __builtin__ module

Since Python looks among the built-in functions after it has checked the local and module namespace,
there may be situations when you need to explicitly refer to the __builtin__ module. For example,
the following script overloads the open function with a version that opens an ordinary file and checks
that it starts with a "magic" string. To be able to use the original open function, it explicitly refers to it
using the module name.
Python Standard Library: Core Modules 1-18

Example: Explicitly accessing functions in the __builtin__ module


# File:builtin-open-example-1.py

def open(filename, mode="rb"):


import __builtin__
file = __builtin__.open(filename, mode)
if file.read(5) not in("GIF87", "GIF89"):
raise IOError, "not a GIF file"
file.seek(0)
return file

fp = open("samples/sample.gif")
print len(fp.read()), "bytes"

fp = open("samples/sample.jpg")
print len(fp.read()), "bytes"

3565 bytes
Traceback (innermost last):
File "builtin-open-example-1.py", line 12, in ?
File "builtin-open-example-1.py", line 5, in open
IOError: not a GIF file
Python Standard Library: Core Modules 1-19

The exceptions module


This module provides the standard exception hierarchy. It's automatically imported when Python
starts, and the exceptions are added to the __builtin__ module. In other words, you usually don't
need to import this module.
This is a Python module in 1.5.2, and a built-in module in 2.0 and later.
The following standard exceptions are defined by this module:
• Exception is used as a base class for all exceptions. It's strongly recommended (but not yet
required) that user exceptions are derived from this class too.
• SystemExit(Exception) is raised by the sys.exit function. If it propagates to the top level
without being caught by a try-except clause, the interpreter is terminated without a traceback
message.
• StandardError(Exception) is used as a base class for all standard exceptions (except
SystemExit, that is).
• KeyboardInterrupt(StandardError) is raised when the user presses Control-C (or any
other interrupt key). Note that this may cause strange errors if you use "catch all" try-except
statements.
• ImportError(StandardError) is raised when Python fails to import a module.
• EnvironmentError is used as a base class for exceptions that can be caused by the
interpreter's environment (that is, they're usually not caused by bugs in the program).
• IOError(EnvironmentError) is used to flag I/O-related errors.
• OSError(EnvironmentError) is used to flag errors by the os module.
• WindowsError(OSError) is used to flag Windows-specific errors from the os module.
• NameError(StandardError) is raised when Python fails to find a global or local name.
• UnboundLocalError(NameError) is raised if your program attempts to access a local
variable before it has been assigned a value. This exception is only used in 2.0 and later; earlier
versions raise a plain NameError exception instead.
• AttributeError(StandardError) is raised when Python fails to find (or assign to) an
instance attribute, a method, a module function, or any other qualified name.
• SyntaxError(StandardError) is raised when the compiler stumbles upon a syntax error.
• (2.0 and later) IndentationError(SyntaxError) is raised for syntax errors caused by bad
indentation. This exception is only used in 2.0 and later; earlier versions raise a plain
SyntaxError exception instead.
• (2.0 and later) TabError(IndentationError) is raised by the interpreter when the -tt option
is used to check for inconsistent indentation. This exception is only used in 2.0 and later;
earlier versions raise a plain SyntaxError exception instead.
Python Standard Library: Core Modules 1-20

• TypeError(StandardError) is raised when an operation cannot be applied to an object of


the given type.
• AssertionError(StandardError) is raised when an assert statement fails (if the
expression is false, that is).
• LookupError(StandardError) is used as a base class for exceptions raised when a
sequence or dictionary type doesn't contain a given index or key.
• IndexError(LookupError) is raised by sequence objects when the given index doesn't exist.
• KeyError(LookupError) is raised by dictionary objects when the given key doesn't exist.
• ArithmeticError(StandardError) is used as a base class for math-related exceptions.
• OverflowError(ArithmeticError) is raised when an operations overflows (for example,
when an integer is too large to fit in the given type).
• ZeroDivisionError(ArithmeticError) is raised when you try to divide a number by zero.
• FloatingPointError(ArithmeticError) is raised when a floating point operation fails.
• ValueError(StandardError) is raised if an argument has the right type, but an invalid
value.
• (2.0 and later) UnicodeError(ValueError) is raised for type problems related to the
Unicode string type. This is only used in 2.0 and later.
• RuntimeError(StandardError) is used for various run-time problems, including attempts
to get outside the box when running in restricted mode, unexpected hardware problems, etc.
• NotImplementedError(RuntimeError) can be used to flag functions that hasn't been
implemented yet, or methods that should be overridden.
• SystemError(StandardError) is raised if the interpreter messes up, and knows about it.
The exception value contains a more detailed description (usually something cryptic, like
"eval_code2: NULL globals" or so). I cannot recall ever seeing this exception in over five
years of full-time Python programming, but maybe that's just me.
• MemoryError(StandardError) is raised when the interpreter runs out of memory. Note
that this only happens when the underlying memory allocation routines complain; you can
often send your poor computer into a mindless swapping frenzy before that happens.

You can create your own exception classes. Just inherit from the built-in Exception class (or a proper
standard exception), and override the constructor and/or __str__ method as necessary.
Python Standard Library: Core Modules 1-21

Example: Using the exceptions module


# File:exceptions-example-1.py

# python imports this module by itself, so the following


# line isn't really needed
# import exceptions

class HTTPError(Exception):
# indicates an HTTP protocol error
def __init__(self, url, errcode, errmsg):
self.url = url
self.errcode = errcode
self.errmsg = errmsg
def __str__(self):
return (
"<HTTPError for %s: %s %s>" %
(self.url, self.errcode, self.errmsg)
)

try:
raise HTTPError("http://www.python.org/foo", 200, "Not Found")
except HTTPError, error:
print "url", "=>", error.url
print "errcode", "=>", error.errcode
print "errmsg", "=>", error.errmsg
raise # reraise exception

url => http://www.python.org/foo


errcode => 200
errmsg => Not Found
Traceback (innermost last):
File "exceptions-example-1", line 16, in ?
HTTPError: <HTTPError for http://www.python.org/foo: 200 Not Found>
Python Standard Library: Core Modules 1-22

The os module
This module provides a unified interface to a number of operating system functions.
Most of the functions in this module are implemented by platform specific modules, such as posix and
nt. The os module automatically loads the right implementation module when it is first imported.

Working with files


The built-in open function lets you create, open, and modify files. This module adds those extra
functions you need to rename and remove files:

Example: Using the os module to rename and remove files


# File:os-example-3.py

import os
import string

def replace(file, search_for, replace_with):


# replace strings in a text file

back = os.path.splitext(file)[0] + ".bak"


temp = os.path.splitext(file)[0] + ".tmp"

try:
# remove old temp file, if any
os.remove(temp)
except os.error:
pass

fi = open(file)
fo = open(temp, "w")

for s in fi.readlines():
fo.write(string.replace(s, search_for, replace_with))

fi.close()
fo.close()

try:
# remove old backup file, if any
os.remove(back)
except os.error:
pass

# rename original to backup...


os.rename(file, back)

# ...and temporary to original


os.rename(temp, file)
Python Standard Library: Core Modules 1-23

#
# try it out!

file = "samples/sample.txt"

replace(file, "hello", "tjena")


replace(file, "tjena", "hello")

Working with directories


The os module also contains a number of functions that work on entire directories.
The listdir function returns a list of all filenames in a given directory. The current and parent directory
markers used on Unix and Windows (. and ..) are not included in this list.

Example: Using the os module to list the files in a directory


# File:os-example-5.py

import os

for file in os.listdir("samples"):


print file

sample.au
sample.jpg
sample.wav
...

The getcwd and chdir functions are used to get and set the current directory:

Example: Using the os module to change the working directory


# File:os-example-4.py

import os

# where are we?


cwd = os.getcwd()
print "1", cwd

# go down
os.chdir("samples")
print "2", os.getcwd()

# go back up
os.chdir(os.pardir)
print "3", os.getcwd()

1 /ematter/librarybook
2 /ematter/librarybook/samples
3 /ematter/librarybook
Python Standard Library: Core Modules 1-24

The makedirs and removedirs functions are used to create and remove directory hierarchies.

Example: Using the os module to create and remove multiple directory levels
# File:os-example-6.py

import os

os.makedirs("test/multiple/levels")

fp = open("test/multiple/levels/file", "w")
fp.write("inspector praline")
fp.close()

# remove the file


os.remove("test/multiple/levels/file")

# and all empty directories above it


os.removedirs("test/multiple/levels")

Note that removedirs removes all empty directories along the given path, starting with the last
directory in the given path name. In contrast, the mkdir and rmdir functions can only handle a single
directory level.

Example: Using the os module to create and remove directories


# File:os-example-7.py

import os

os.mkdir("test")
os.rmdir("test")

os.rmdir("samples") # this will fail

Traceback (innermost last):


File "os-example-7", line 6, in ?
OSError: [Errno 41] Directory not empty: 'samples'

To remove non-empty directories, you can use the rmtree function in the shutil module.

Working with file attributes

The stat function fetches information about an existing file. It returns a 9-tuple which contains the
size, inode change timestamp, modification timestamp, and access privileges.
Python Standard Library: Core Modules 1-25

Example: Using the os module to get information about a file


# File:os-example-1.py

import os
import time

file = "samples/sample.jpg"

def dump(st):
mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime = st
print "- size:", size, "bytes"
print "- owner:", uid, gid
print "- created:", time.ctime(ctime)
print "- last accessed:", time.ctime(atime)
print "- last modified:", time.ctime(mtime)
print "- mode:", oct(mode)
print "- inode/dev:", ino, dev

#
# get stats for a filename

st = os.stat(file)

print "stat", file


dump(st)
print

#
# get stats for an open file

fp = open(file)

st = os.fstat(fp.fileno())

print "fstat", file


dump(st)

stat samples/sample.jpg
- size: 4762 bytes
- owner: 0 0
- created: Tue Sep 07 22:45:58 1999
- last accessed: Sun Sep 19 00:00:00 1999
- last modified: Sun May 19 01:42:16 1996
- mode: 0100666
- inode/dev: 0 2

fstat samples/sample.jpg
- size: 4762 bytes
- owner: 0 0
- created: Tue Sep 07 22:45:58 1999
- last accessed: Sun Sep 19 00:00:00 1999
- last modified: Sun May 19 01:42:16 1996
- mode: 0100666
- inode/dev: 0 0
Python Standard Library: Core Modules 1-26

Some fields don't make sense on non-Unix platforms; for example, the (inode, dev) tuple provides a
unique identity for each file on Unix, but can contain arbitrary data on other platforms.
The stat module contains a number of useful constants and helper functions for dealing with the
members of the stat tuple. Some of these are shown in the examples below.

You can modify the mode and time fields using the chmod and utime functions:

Example: Using the os module to change a file's privileges and timestamps


# File:os-example-2.py

import os
import stat, time

infile = "samples/sample.jpg"
outfile = "out.jpg"

# copy contents
fi = open(infile, "rb")
fo = open(outfile, "wb")

while 1:
s = fi.read(10000)
if not s:
break
fo.write(s)

fi.close()
fo.close()

# copy mode and timestamp


st = os.stat(infile)
os.chmod(outfile, stat.S_IMODE(st[stat.ST_MODE]))
os.utime(outfile, (st[stat.ST_ATIME], st[stat.ST_MTIME]))

print "original", "=>"


print "mode", oct(stat.S_IMODE(st[stat.ST_MODE]))
print "atime", time.ctime(st[stat.ST_ATIME])
print "mtime", time.ctime(st[stat.ST_MTIME])

print "copy", "=>"


st = os.stat(outfile)
print "mode", oct(stat.S_IMODE(st[stat.ST_MODE]))
print "atime", time.ctime(st[stat.ST_ATIME])
print "mtime", time.ctime(st[stat.ST_MTIME])

original =>
mode 0666
atime Thu Oct 14 15:15:50 1999
mtime Mon Nov 13 15:42:36 1995
copy =>
mode 0666
atime Thu Oct 14 15:15:50 1999
mtime Mon Nov 13 15:42:36 1995
Python Standard Library: Core Modules 1-27

Working with processes

The system function runs a new command under the current process, and waits for it to finish.

Example: Using the os module to run an operating system command


# File:os-example-8.py

import os

if os.name == "nt":
command = "dir"
else:
command = "ls -l"

os.system(command)

-rwxrw-r-- 1 effbot effbot 76 Oct 9 14:17 README


-rwxrw-r-- 1 effbot effbot 1727 Oct 7 19:00 SimpleAsyncHTTP.py
-rwxrw-r-- 1 effbot effbot 314 Oct 7 20:29 aifc-example-1.py
-rwxrw-r-- 1 effbot effbot 259 Oct 7 20:38 anydbm-example-1.py
...

The command is run via the operating system's standard shell, and returns the shell's exit status.
Under Windows 95/98, the shell is usually command.com whose exit status is always 0.

Warning:

Since os.system passes the command on to the shell as is, it can be


dangerous to use if you don't check the arguments carefully (consider
running os.system("viewer %s" % file) with the file variable set to
"sample.jpg; rm -rf $HOME"). When unsure, it's usually better to
use exec or spawn instead (see below).

The exec function starts a new process, replacing the current one ("go to process", in other words). In
the following example, note that the "goodbye" message is never printed:

Example: Using the os module to start a new process


# File:os-exec-example-1.py

import os
import sys

program = "python"
arguments = ["hello.py"]

print os.execvp(program, (program,) + tuple(arguments))


print "goodbye"

hello again, and welcome to the show

Python provides a whole bunch of exec functions, with slightly varying behavior. The above example
uses execvp, which searches for the program along the standard path, passes the contents of the
Python Standard Library: Core Modules 1-28

second argument tuple as individual arguments to that program, and runs it with the current set of
environment variables. See the Python Library Reference for more information on the other seven
ways to call this function.
Under Unix, you can call other programs from the current one by combining exec with two other
functions, fork and wait. The former makes a copy of the current process, the latter waits for a child
process to finish.

Example: Using the os module to run another program (Unix)


# File:os-exec-example-2.py

import os
import sys

def run(program, *args):


pid = os.fork()
if not pid:
os.execvp(program, (program,) + args)
return os.wait()[0]

run("python", "hello.py")

print "goodbye"

hello again, and welcome to the show


goodbye

The fork returns zero in the new process (the return from fork is the first thing that happens in that
process!), and a non-zero process identifier in the original process. Or in other words, "not pid" is true
only if we're in the new process.
fork and wait are not available on Windows, but you can use the spawn function instead.
Unfortunately, there's no standard version of spawn that searches for an executable along the path, so
you have to do that yourself:

Example: Using the os module to run another program (Windows)


# File:os-spawn-example-1.py

import os
import string

def run(program, *args):


# find executable
for path in string.split(os.environ["PATH"], os.pathsep):
file = os.path.join(path, program) + ".exe"
try:
return os.spawnv(os.P_WAIT, file, (file,) + args)
except os.error:
pass
raise os.error, "cannot find executable"

run("python", "hello.py")
Python Standard Library: Core Modules 1-29

print "goodbye"

hello again, and welcome to the show


goodbye

You can also use spawn to run other programs in the background. The following example adds an
optional mode argument to the run function; when set to os.P_NOWAIT, the script doesn't wait for
the other program to finish.
The default flag value os.P_WAIT tells spawn to wait until the new process is finished. Other flags
include os.P_OVERLAY which makes spawn behave like exec, and os.P_DETACH which runs
the new process in the background, detached from both console and keyboard.

Example: Using the os module to run another program in the background (Windows)
# File:os-spawn-example-2.py

import os
import string

def run(program, *args, **kw):


# find executable
mode = kw.get("mode", os.P_WAIT)
for path in string.split(os.environ["PATH"], os.pathsep):
file = os.path.join(path, program) + ".exe"
try:
return os.spawnv(mode, file, (file,) + args)
except os.error:
pass
raise os.error, "cannot find executable"

run("python", "hello.py", mode=os.P_NOWAIT)


print "goodbye"

goodbye
hello again, and welcome to the show
Python Standard Library: Core Modules 1-30

The following example provides a spawn method that works on either platform:

Example: Using either spawn or fork/exec to run another program


# File:os-spawn-example-3.py

import os
import string

if os.name in ("nt", "dos"):


exefile = ".exe"
else:
exefile = ""

def spawn(program, *args):


try:
# check if the os module provides a shortcut
return os.spawnvp(program, (program,) + args)
except AttributeError:
pass
try:
spawnv = os.spawnv
except AttributeError:
# assume it's unix
pid = os.fork()
if not pid:
os.execvp(program, (program,) + args)
return os.wait()[0]
else:
# got spawnv but no spawnp: go look for an executable
for path in string.split(os.environ["PATH"], os.pathsep):
file = os.path.join(path, program) + exefile
try:
return spawnv(os.P_WAIT, file, (file,) + args)
except os.error:
pass
raise IOError, "cannot find executable"

#
# try it out!

spawn("python", "hello.py")

print "goodbye"

hello again, and welcome to the show


goodbye

The above example first attempts to call a function named spawnvp. If that doesn't exist (it doesn't, in
2.0 and earlier), the function looks for a function named spawnv and searches the path all by itself. As
a last resort, it falls back on exec and fork.
Python Standard Library: Core Modules 1-31

Working with daemon processes

On Unix, fork can also be used to turn the current process into a background process (a "daemon").
Basically, all you need to do is to fork off a copy of the current process, and terminate the original
process:

Example: Using the os module to run as daemon (Unix)


# File:os-example-14.py

import os
import time

pid = os.fork()
if pid:
os._exit(0) # kill original

print "daemon started"


time.sleep(10)
print "daemon terminated"

However, it takes a bit more work to create a real daemon. First, call setpgrp to make the new process
a "process group leader". Otherwise, signals sent to a (by that time) unrelated process group might
cause problems in your daemon:
os.setpgrp()

It's also a good idea to remove the user mode mask, to make sure files created by the daemon actually
gets the mode flags specified by the program:
os.umask(0)

Then, you should redirect the stdout/stderr files, instead of just closing them. If you don't do this, you
may get unexpected exceptions the day some of your code tries to write something to the console via
stdout or stderr.
class NullDevice:
def write(self, s):
pass

sys.stdin.close()
sys.stdout = NullDevice()
sys.stderr = NullDevice()

In other words, while Python's print and C's printf/fprintf won't crash your program if the devices
have been disconnected, sys.stdout.write() happily throws an IOError exception when the
application runs as a daemon. But your program works just fine when running in the foreground...
Python Standard Library: Core Modules 1-32

By the way, the _exit function used in the examples above terminates the current process. In contrast
to sys.exit, this works also if the caller happens to catch the SystemExit exception:

Example: Using the os module to exit the current process


# File:os-example-9.py

import os
import sys

try:
sys.exit(1)
except SystemExit, value:
print "caught exit(%s)" % value

try:
os._exit(2)
except SystemExit, value:
print "caught exit(%s)" % value

print "bye!"

caught exit(1)
Python Standard Library: Core Modules 1-33

The os.path module


This module contains functions that deal with long filenames (path names) in various ways. To use this
module, import the os module, and access this module as os.path.

Working with file names


This module contains a number of functions that deal with long filenames in a platform independent
way. In other words, without having to deal with forward and backward slashes, colons, and whatnot.

Example: Using the os.path module to handle filename


# File:os-path-example-1.py

import os

filename = "my/little/pony"

print "using", os.name, "..."


print "split", "=>", os.path.split(filename)
print "splitext", "=>", os.path.splitext(filename)
print "dirname", "=>", os.path.dirname(filename)
print "basename", "=>", os.path.basename(filename)
print "join", "=>", os.path.join(os.path.dirname(filename),
os.path.basename(filename))

using nt ...
split => ('my/little', 'pony')
splitext => ('my/little/pony', '')
dirname => my/little
basename => pony
join => my/little\pony

Note that split only splits off a single item.


Python Standard Library: Core Modules 1-34

This module also contains a number of functions that allow you to quickly figure out what a filename
represents:

Example: Using the os.path module to check what a filename represents


# File:os-path-example-2.py

import os

FILES = (
os.curdir,
"/",
"file",
"/file",
"samples",
"samples/sample.jpg",
"directory/file",
"../directory/file",
"/directory/file"
)

for file in FILES:


print file, "=>",
if os.path.exists(file):
print "EXISTS",
if os.path.isabs(file):
print "ISABS",
if os.path.isdir(file):
print "ISDIR",
if os.path.isfile(file):
print "ISFILE",
if os.path.islink(file):
print "ISLINK",
if os.path.ismount(file):
print "ISMOUNT",
print

. => EXISTS ISDIR


/ => EXISTS ISABS ISDIR ISMOUNT
file =>
/file => ISABS
samples => EXISTS ISDIR
samples/sample.jpg => EXISTS ISFILE
directory/file =>
../directory/file =>
/directory/file => ISABS
Python Standard Library: Core Modules 1-35

The expanduser function treats a user name shortcut in the same way as most modern Unix shells (it
doesn't work well on Windows).

Example: Using the os.path module to insert the user name into a filename
# File:os-path-expanduser-example-1.py

import os

print os.path.expanduser("~/.pythonrc")

/home/effbot/.pythonrc

The expandvars function inserts environment variables into a filename:

Example: Using the os.path module to insert variables into a filename


# File:os-path-expandvars-example-1.py

import os

os.environ["USER"] = "user"

print os.path.expandvars("/home/$USER/config")
print os.path.expandvars("$USER/folders")

/home/user/config
user/folders

Traversing a file system

The walk function helps you find all files in a directory tree. It takes a directory name, a callback
function, and a data object that is passed on to the callback.

Example: Using the os.path module to traverse a file system


# File:os-path-walk-example-1.py

import os

def callback(arg, directory, files):


for file in files:
print os.path.join(directory, file), repr(arg)

os.path.walk(".", callback, "secret message")


Python Standard Library: Core Modules 1-36

./aifc-example-1.py 'secret message'


./anydbm-example-1.py 'secret message'
./array-example-1.py 'secret message'
...
./samples 'secret message'
./samples/sample.jpg 'secret message'
./samples/sample.txt 'secret message'
./samples/sample.zip 'secret message'
./samples/articles 'secret message'
./samples/articles/article-1.txt 'secret message'
./samples/articles/article-2.txt 'secret message'
...

The walk function has a somewhat obscure user interface (maybe it's just me, but I can never
remember the order of the arguments). The index function in the next example returns a list of
filenames instead, which lets you use a straightforward for-in loop to process the files:

Example: Using os.listdir to traverse a file system


# File:os-path-walk-example-2.py

import os

def index(directory):
# like os.listdir, but traverses directory trees
stack = [directory]
files = []
while stack:
directory = stack.pop()
for file in os.listdir(directory):
fullname = os.path.join(directory, file)
files.append(fullname)
if os.path.isdir(fullname) and not os.path.islink(fullname):
stack.append(fullname)
return files

for file in index("."):


print file

.\aifc-example-1.py
.\anydbm-example-1.py
.\array-example-1.py
...
Python Standard Library: Core Modules 1-37

If you don't want to list all files (for performance or memory reasons), the following example uses a
different approach. Here, the DirectoryWalker class behaves like a sequence object, returning one
file at a time:

Example: Using a directory walker to traverse a file system


# File:os-path-walk-example-3.py

import os

class DirectoryWalker:
# a forward iterator that traverses a directory tree

def __init__(self, directory):


self.stack = [directory]
self.files = []
self.index = 0

def __getitem__(self, index):


while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
self.index = 0
else:
# got a filename
fullname = os.path.join(self.directory, file)
if os.path.isdir(fullname) and not os.path.islink(fullname):
self.stack.append(fullname)
return fullname

for file in DirectoryWalker("."):


print file

.\aifc-example-1.py
.\anydbm-example-1.py
.\array-example-1.py
...

Note that this class doesn't check the index passed to the __getitem__ method. This means that it
won't do the right thing if you access the sequence members out of order.
Python Standard Library: Core Modules 1-38

Finally, if you're interested in the file sizes or timestamps, here's a version of the class that returns both
the filename and the tuple returned from os.stat. This version saves one or two stat calls for each file
(both os.path.isdir and os.path.islink uses stat), and runs quite a bit faster on some platforms.

Example: Using a directory walker to traverse a file system, returning both the filename
and additional file information
# File:os-path-walk-example-4.py

import os, stat

class DirectoryStatWalker:
# a forward iterator that traverses a directory tree, and
# returns the filename and additional file information

def __init__(self, directory):


self.stack = [directory]
self.files = []
self.index = 0

def __getitem__(self, index):


while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
self.index = 0
else:
# got a filename
fullname = os.path.join(self.directory, file)
st = os.stat(fullname)
mode = st[stat.ST_MODE]
if stat.S_ISDIR(mode) and not stat.S_ISLNK(mode):
self.stack.append(fullname)
return fullname, st

for file, st in DirectoryStatWalker("."):


print file, st[stat.ST_SIZE]

.\aifc-example-1.py 336
.\anydbm-example-1.py 244
.\array-example-1.py 526
Python Standard Library: Core Modules 1-39

The stat module


This module contains a number of constants and test functions that can be used with the os.stat
function.

Example: Using the stat module


# File:stat-example-1.py

import stat
import os, time

st = os.stat("samples/sample.txt")

print "mode", "=>", oct(stat.S_IMODE(st[stat.ST_MODE]))

print "type", "=>",


if stat.S_ISDIR(st[stat.ST_MODE]):
print "DIRECTORY",
if stat.S_ISREG(st[stat.ST_MODE]):
print "REGULAR",
if stat.S_ISLNK(st[stat.ST_MODE]):
print "LINK",
print

print "size", "=>", st[stat.ST_SIZE]

print "last accessed", "=>", time.ctime(st[stat.ST_ATIME])


print "last modified", "=>", time.ctime(st[stat.ST_MTIME])
print "inode changed", "=>", time.ctime(st[stat.ST_CTIME])

mode => 0664


type => REGULAR
size => 305
last accessed => Sun Oct 10 22:12:30 1999
last modified => Sun Oct 10 18:39:37 1999
inode changed => Sun Oct 10 15:26:38 1999
Python Standard Library: Core Modules 1-40

The string module


This module contains a number of functions to process standard Python strings.

Example: Using the string module


# File:string-example-1.py

import string

text = "Monty Python's Flying Circus"

print "upper", "=>", string.upper(text)


print "lower", "=>", string.lower(text)
print "split", "=>", string.split(text)
print "join", "=>", string.join(string.split(text), "+")
print "replace", "=>", string.replace(text, "Python", "Java")
print "find", "=>", string.find(text, "Python"), string.find(text, "Java")
print "count", "=>", string.count(text, "n")

upper => MONTY PYTHON'S FLYING CIRCUS


lower => monty python's flying circus
split => ['Monty', "Python's", 'Flying', 'Circus']
join => Monty+Python's+Flying+Circus
replace => Monty Java's Flying Circus
find => 6 -1
count => 3

In Python 1.5.2 and earlier, this module uses functions from the strop implementation module where
possible.
In Python 1.6 and later, most string operations are made available as string methods as well, and many
functions in the string module are simply wrapper functions that call the corresponding string
method.

Example: Using string methods instead of string module functions (Python 1.6 and later)
# File:string-example-2.py

text = "Monty Python's Flying Circus"

print "upper", "=>", text.upper()


print "lower", "=>", text.lower()
print "split", "=>", text.split()
print "join", "=>", "+".join(text.split())
print "replace", "=>", text.replace("Python", "Perl")
print "find", "=>", text.find("Python"), text.find("Perl")
print "count", "=>", text.count("n")
Python Standard Library: Core Modules 1-41

upper => MONTY PYTHON'S FLYING CIRCUS


lower => monty python's flying circus
split => ['Monty', "Python's", 'Flying', 'Circus']
join => Monty+Python's+Flying+Circus
replace => Monty Perl's Flying Circus
find => 6 -1
count => 3

In addition to the string manipulation stuff, the string module also contains a number of functions
which convert strings to other types:

Example: Using the string module to convert strings to numbers


# File:string-example-3.py

import string

print int("4711"),
print string.atoi("4711"),
print string.atoi("11147", 8), # octal
print string.atoi("1267", 16), # hexadecimal
print string.atoi("3mv", 36) # whatever...

print string.atoi("4711", 0),


print string.atoi("04711", 0),
print string.atoi("0x4711", 0)

print float("4711"),
print string.atof("1"),
print string.atof("1.23e5")

4711 4711 4711 4711 4711


4711 2505 18193
4711.0 1.0 123000.0

In most cases (especially if you're using 1.6 or later), you can use the int and float functions instead of
their string module counterparts.
The atoi function takes an optional second argument, which specifices the number base. If the base is
zero, the function looks at the first few characters before attempting to interpret the value: if "0x", the
base is set to 16 (hexadecimal), and if "0", the base is set to 8 (octal). The default is base 10 (decimal),
just as if you hadn't provided an extra argument.
In 1.6 and later, the int also accepts a second argument, just like atoi. But unlike the string versions,
int and float also accepts Unicode strings.
Python Standard Library: Core Modules 1-42

The re module
"Some people, when confronted with a problem, think "I know, I'll use
regular expressions." Now they have two problems"

Jamie Zawinski, on comp.lang.emacs

This module provides a set of powerful regular expression facilities. A regular expression is a string
pattern written in a compact (and quite cryptic) syntax, and this module allows you to quickly check
whether a given string matches a given pattern (using the match function), or contains such a pattern
(using the search function).
The match function attempts to match a pattern against the beginning of the given string. If the
pattern matches anything at all (including an empty string, if the pattern allows that!), match returns
a match object. The group method can be used to find out what matched.

Example: Using the re module to match strings


# File:re-example-1.py

import re

text = "The Attila the Hun Show"

# a single character
m = re.match(".", text)
if m: print repr("."), "=>", repr(m.group(0))

# any string of characters


m = re.match(".*", text)
if m: print repr(".*"), "=>", repr(m.group(0))

# a string of letters (at least one)


m = re.match("\w+", text)
if m: print repr("\w+"), "=>", repr(m.group(0))

# a string of digits
m = re.match("\d+", text)
if m: print repr("\d+"), "=>", repr(m.group(0))

'.' => 'T'


'.*' => 'The Attila the Hun Show'
'\\w+' => 'The'
Other documents randomly have
different content
“IF LOVE WERE ALL.”
(PRISONER OF ZENDA.)

“If love were all!” Can love be less than all


Here in the world the God of Love hath made?
If love were all—and love were unafraid,
And knew not death’s corrupting funeral pall!

Oh Princess, with thy soul by heavenly call


In love’s divinest panoply arrayed,
Hath thy soul-sight thy love-sight so betrayed
That love from his supremest place should fall?

Yet wert thou right. Thy woman’s heart divined


The soul of love’s transcendent perfectness:
For like a star within a mist confined
And burning thro’ love’s soul is righteousness.

Thus love is all—tho’, as on Calvary,


Renunciation love’s fulfillment be!

Edith Neil.
THE MAN ON A BICYCLE.
The man on a bicycle came panting up a hill at the beginning of a
large town.
“Hello! Knickerbockers,” cried the man on foot; “do you call that
the gait for a scorcher? Why, it aint more’n a pair uv bars.”
“That’s all right, little boy,” returned he of the wheel.
“Little boy, yourself! Didn’t you know it was five dollars fine for
ridin’ on the sidewalk?”
“Is it? All right? I’ll pay when I come back;” and the man on a
bicycle, encountering a level piece of road, put an end to further
conversation by a sudden spurt.
But the cyclometer was not to make a steady advance that
evening. A surface crossing lay ahead, blocked by a belated freight
train. The engineer knew his business and meddled continually with
the throttle. After going about two car-lengths in one direction, the
train would stop, remember something left behind, and back up. That
is the way to keep a crowd pacific. Give them plenty to hope for and
they forget to fight.
The wheelman rode in slow circles for a while, but finding the
slush and snow too deep for this exercise, was forced to a
humiliating dismount.
“Misder!” shouted a dirty urchin with a cold, “did yer know yer
’adn’d god no lighd? Fibe dollars fine an’ the cop’s in the deepo.”
“O, break away, break away!” snarled the wheelman.
“Young man,” lisped a willy boy, “I thought those things weah
called in, you know.”
“I wish some one would call that thing in.”
This retort was pointed at the willy boy, and raised a laugh.
“How long are they going to keep us waiting here in the cold?”
muttered a querulous old gentleman. “It’s against the law, and the
company ought to be prosecuted.”
“The present company?” ventured a bashful young man, who was
dressed as if going somewhere.
“No, the present company is always excepted,” came from
obscurity.
The man with a bicycle snapped his bell uneasily. He was in a
hurry, of course; if you live much on a wheel, hurry becomes chronic,
engendered perhaps by the accustomed sense of rapid motion; but,
like many of his class, he had that fellow feeling for petty law
breakers, which comes by taking chances against city ordinances.
The fellow at the valve was taking his chances too, with excellent
success. The patience of an American crowd approaches the
miraculous. Fifty engagements were being broken and ten times as
many toes were freezing, all because one railroader was too lazy to
draw a coupling-pin. Yet so long as the cars continued to move, no
one felt called upon to interfere.
“How many minutes may a crossing legally be blocked?”
demanded the querulous old gentleman, pulling out his watch.
“Ten, I believe,” answered the flagman, soothingly.
“Ten? Why, we’ve been here most fifteen now!”
“S’posin’ that train on the down track ud move up just as this un
was movin’ away, which ud you have ’rested then?”
The querulous old gentleman looked at the newsboy reprovingly,
but said nothing.
“Might try and have the president pulled,” suggested some one.
“What of? The Road? Wopey dick! He’s got a pull himself.”
The newsboy smiled approvingly upon his mot, during a silence
that might be felt. It was a relief when the wind picked up the tones
of a brass band, playing in front of the theatre, and wafted them in
that direction.
“Sub ud oughd to pud runners on thad bike, see?” volunteered the
dirty urchin with a cold.
This aroused the newsboy to a stroke of business.
“New Yawk Evening Sun or Worl! One cent! Sunorworl?”
Here the bashful young man who was dressed as if going
somewhere, separated himself, and cried:
“Conductor, cut this train in two, or I will have you arrested.”
“There, you’re done!”
“Cut it short!”
“Go, take a walk!”
were expressions which greeted this sally.
The bashful young man took up the thread of his private life where
it had broken off, and wished he had separated himself further.
A touch on the sleeve aroused the man with a bicycle. There stood
the man on foot.
“Hello! Knickerbockers. Horse tied, eh? Thought I’d ketch up to
you. Where is your century run? Didn’t I say that there was no
scorchin’ gait?”
The man with a bicycle said something that commenced with
“damn,” and then, seeing a pale frightened-looking girl near by,
wished he hadn’t. In the forgetfulness of his remorse he smirched
the newsboy with his machine.
“You most certainly want to get done hittin’ me with that there last
year’s safety,” began the latter, speaking loud enough to be heard by
all—but his philippic was cut short by the arrival of train orders, and
the clearing of the road. The man with a bicycle did a handsome
pedal mount and spun skillfully through the surging mob, catching
cries of “See that burning safety!” “Gimmie a ride, boss?” and the
like, from those left behind. But the man on a wheel continued to
ride.
The man on foot continued to walk.
And the band played on.
Harvey Lewis Wickham.
THE STEWARD.
A BALLAD OF DEATH.

A Beggar wandered forth to beg.


(A soul may dwell in Heaven or Hell.)
At night he groaned aloud, when passed
One bearing stores the King wished last.

“Now give me food, for the dear Christ’s sake,”


(Or Heaven or Hell—O, choose ye well.)
Moaned he the weak, stretching his hand.
I trow men fear the final strand.

The Steward stopped, and smiled, and bowed.


(One ward may tell of Heaven or Hell.)
Softly he spoke: “A fitting thing,
To give you food and rob the King!”

The one moved on, the one moved not.


(A soul may dwell in Heaven or Hell.)
The Steward sold one half the bread.
Next morning the Beggar was dead.

The jester told the King the tale.


(A soul shall dwell in Heaven or Hell.)
A woman gazing at the King,
Shrieked—to his knees she did not cling.

The King’s sword pushed the Steward on,


(Who can foretell the depths of Hell?)
And the King smiled as on the band
Outside a door he laid his hand.

C. P. N.
LET THERE BE GALL ENOUGH IN
THY INK.—Twelfth Night.
’Tis an odd old world, this of ours that is round like an orange, and
slightly flattened at the poles. It drives not well, and it hath but
moderate fondness for gall. Why, then, seek to drive it? Why harass
it with the hurtful attrition of gall-dippen pens? For in truth, its small
love for gall is yet greater than its use therefor. It needs not that we
should make it smart. ’Tis smart enough, and clever enough, already,
towering the hearts of the angels, and affording a spectacle for the
little fishes. Application of gall will not help it. Rightly used, a little
may ease thy own jaundice, but in thy ink it erodes the pen that uses
it.
Are we vexed at the follies of the round old world? Is our taste
offended by the unripe things written and painted and sung by those
who are not perfect as we are? We ought to consider the words of
the gentle stoic: “For it is natural that these things should be done by
such persons. It is a matter of necessity, and if a man will not have it
so he will not allow the fig-tree to have juice.”
To what end do we Philistines write? Is it not because we are
seeking after the truth? Is it not for the expression of that which to us
seems beautiful and helpful and desirable to be in the world?
And for what, let us suppose, do the armies of the aliens put pen
to paper? Is it not for the same end? And if they see not purely, do
we then hope to clarify their vision with gall? Rather we ought not to
thwart them in the pursuit of that which seems to them excellent and
worthy of effort. It is unphilosophic, and in contravention to the
scientific spirit, to deny others the right which we claim for ourselves.
We ought rather to do the thing which to us seems lovely, and let
that protest, for us, against unloveliness, by its life and realty—the
only effectual protest this world has ever known. Already there is too
much of strife, too much of denial in the world. Nature argues the
questioning life in the affirmative, for well she knows, the ancient
wise one, that denial is deadly. “I believe” is the password into the
secret places of good.
The single vision, that sees truest, the simple heart, that loves it;
the direct thought that sends it forth to bless—the world needs these
more than that we should camp upon its trail with gall in our ink and
our pens tipped with bitterness.
Gall can never fill a vacuum. “If you don’t want a boy to do that,”
said a wise teacher (putting thumb to nose), “teach him something
prettier.”
This, then, must we do for this hulking schoolboy world of ours; the
half-grown, growing world, that knows enough to recognize that gall
is neither good nor beautiful, yet sees not that the thing it does is, as
well, unlovely.
Let us strive to look out on life with open vision and simple soul,
seeing that it is fair; that no plant cometh forth to face the winter’s
blight, but when the winter is over then green, tender things of
beauty push upwards to meet the sunshine—first the blade, then the
ear, and after that the full corn in the ear. Then cometh the insect,
with his drop of gall, and ugliness and excrescence follow.
That which gives heat and light and blessing; that which generates
force, and yields beauty in the burning wood that cheers our hearth,
is the warm brightness of the sun’s rays that, in the process of
liberating oxygen into the outer air, were stored up in the growing
tree. If these had not been actually caught and incorporated in the
wood by Nature’s subtle chemistry, do you think the fire would warm
us, sitting by it?
And that in our literature, and in our art, that shall make them real,
and able to offer coming ages anything in the warmth and light of
this, must be what we shall manage to incorporate with their growth
of the pure and wholesome, the life-making forces of our time.
Negation is not life. Disease is not power. Abnormality is not truth.
These are forces that make for death; and life, in its scientific
ultimate, is the sum-total of the forces that resist death. So, I say
again, that work of ours which is to carry life forward, which is to
warm and light the ages, must be what we can perpetuate of the life-
giving, growing elements of this one. Let there be gall enough in thy
ink. To what purpose? Gall is not a promoter of growth. It is a result
of hurt, and where it touches it leaves even a bad thing worse than it
found it.
Adeline Knapp.
THE WORSHIPPERS.
Now it came to pass in the still night watches, when my body was
asleep, that my soul dreamed a dream.
And in my dream I heard a voice say, “Unstop his ears that he may
hear.”
And I became aware of the presence of an Angel, and he touched
mine ears, saying, “When thou hearest a sound, a great sound, as of
many mighty waters rushing headlong, listen, and fear nothing.”
Then, verily, did burst on my hearing a mighty noise, a most
discordant frush, and I stretched out my hand to the Angel, who said,
“Fear not! Now tell me what thou hearest.”
After pondering a long time I turned me to the Angel and said,
“This discordant sound is that of many and diverse petitions, of
which some are directed to the Eternal but more to the Spirit of Evil. I
further perceive that well-nigh each and every voice thinks its own
tone the right and the only right tone, and some few voices there be
which desire all the others destroyed. Yet, I hear faintly a few that are
as pure and sweet as the voices of the morning stars when they sing
together.”
And the Angel said, “These are all the voices of the religions, the
sects, the churches, and the individual hearts, upon your planet.
They are many in number. They are wondrously many in number.
Yet, the understanding of your little heart is darkened: none of these
petitions are directed to the Spirit of Evil, though only God and we
know the heart of man, and the love of only God is great enough to
forgive your many strange desires. Those few and sweet voices—
ah! those few sweet voices redeem—redeem the world!”
As I listened again to the strange murmur I wept, and cried saying,
“Would that these voices were as one!”
And the Angel answered and said, “They will be when in that state
you call ‘Heaven.’”
Then did my soul face eagerly the face of the Angel and say to
him, “They will verily attain Heaven, then—all these many jangling
voices?”
Bending on me a wondering look he answered, “They will. All who
strive for Right and Light shall be happy. Worship they not all as truly
and deeply as they know? Strive they not all to love—to be unselfish,
although some half-heartedly? From the north and the south, from
the east and the west shall they be gathered, and there shall
carilloux harmonious ascend to The Eternal, as from one sweet and
glorified tongue.”
And as I listened again I sighed and said, “God is very patient.”
“God is very patient. He is Love, and his ways are past finding
out,” murmured the Angel.
Again he touched mine ears, saying, “Have you learned? Go,
return to earth, and live in the spirit of Love. Love, and judge not.
Love, and be very charitable, for you yourself jar on Heaven’s
peace.”
And I awoke, and beheld the impartial sun.
Charles P. Nettleton.
side talks with the philistines:
being soul easement and
wisdom incidentally.
The Sons of Melchizedek are a most peculiar people.
So far as I know the Society for Psychic Research has not yet
taken up the subject of these men who are without beginning of days
or end of time. Yet surely it is a most vital theme. These beings who
were never born and cannot die form a tribe that obeys no natural
edict—they are a law unto themselves. They appear and disappear,
like Clangingharp, to reappear again. Like vagrant comets, their orbit
cannot be determined.
They are visible only under peculiar and extraordinary conditions.
They materialize at will and disappear without explanation. After a
lecture I have seen one of them rush forward and greet the speaker
with a glow that must have gladdened the orator’s heart for months.
In fact, your son of Melchizedek is an orator himself and therefore
knows the orator’s need for a fervent word of appreciation after his
“effort.”
Once at a Methodist love feast, when there was a lull in the
program and the minister asked “And is there not just one more who
is willing to add a word of testimony?” I felt a slight cold feeling go
over me and knew at once that the Unknown was rising to his feet
behind. I heard him clear his throat and begin with “My friends, I
have been thinking while sitting here,” in a low, musical voice—a
voice all a-tremble with fervor. He spoke for fully fifteen minutes—
spoke with ease, and to the point. At first there was a craning of
necks and whispered questions as to who he was; but this was soon
lost in admiration. After the service he shook hands with many, then
disappeared, none knew where.
This mysterious being often helps to carry in the piano, and in
crowded street cars he has been known to supply the necessary
nickle when ladies could not find their pockets. When old gentlemen
fall in a fit on the street, he is on hand. Should a woman faint in
church, he gently carries her out. He opens the windows in cars, and
looks after the ventilator at all times, and at barbecues and outdoor
public meetings he calls up the stranger to the feast, introducing shy
countrymen to others still more shy, thus thawing the social ice and
making all secure.
When church debts are to be raised he sometimes arises in his
seat and subscribes a large amount. At mass meetings where
volunteers are called for to pass the hat he always responds. He
greets you cordially on the railway train, shaking hands as he
passes; asks after the wife and babies and shames you into smirking
idiocy because you cannot call him by name, and as he departs he
waves his hand and charges you thus: “Take care yourself, old man!”
He is always large, usually stout, and the true type has a dun
colored chin whisker. At least he should have.
He carries a glow of good nature that warms like wine; he is never
cast down, nor is his heart dismayed. At country funerals he often
appears, consoles the friends, takes care of the flowers, and
arranges the chairs in a column circle against the wall. At the
churchyard he walks with uncovered head by the side of the
clergyman, fetches the reins from the nearest team to lower the
coffin, and handles the shovel with an unction that savors of joy.
Surely, the Sons of Melchizedek, although not Philistines, are
Peculiar Persons.
She—“Don’t you think him rather thick-headed?”
He—(Who has lately been presented with a book of Familiar
Quotations) “Yes, indeed: his head is as thick as leaves in
Vallombrosa.”
The most biting bit of irony that passes as a current coin is that
reference to Boston as a city of culture—or it would be, were it not
for the insight shown in Paragraphs.
There were two Ballestiers. The good one, beloved of the gods
(and men), died young; but the one that resides near Brattleboro will
probably live to be a hundred. Rudyard benefitted the man and as a
sure result got his enmity. He is just literary enough in his instincts to
read his brother-in-law’s books for gibes and jeers at himself. He
imagines that every villain in the Kipling books is a black attempt to
paint a Beatty Ballestier portrait: not knowing that an author (like
Diety) creates in his own image. So the Ballestier reads and rages
and cuts hickory clubs and lies in wait for Mowgli, who dares not
venture out of sight of the bungalow except after dark. Has Rudyard
Kipling written the best he ever will? is a question that the bad
Ballestier proposes to answer by sending the soul of Kipling to join
that of Tomlinson. Some folks are saying “Good hunting to you, Kaa
Ballestier,” but Kipling in the meantime has had the rogue elephant
put under bonds to keep the peace, this as preliminary to the killing,
should the rogue continue to fool around the ’rickshaw.
In the story of “Kate Carnegie,” now running in The Bookman,
Ian Maclaren uses the exclamation “Dod!” about three times to a
page. This is understood to be a little advertising scheme suggested
by Mr. MacArthur. Your Scot is a very thrifty person.
Mr. Percival Pollard who fights in the Commissariat, and once
received a red badge, by being bumbasted with a pie (although he
swears ’twas a tart) is uttering rank heresy in the New York Journal
concerning Stephen Crane. The statement is made that Crane is
only a producer of “Bloomingdale symbolistic hash.” But now behold
Mr. Pollard has discovered Nankivell “King of Colorists and Past
Master of all living Draughtsmen”—bless my soul! when up pops a
writer in the Art Amateur and declares that the only fit man to
illustrate The Black Riders is this same Nankivell.
They do say that ’Enery James has resolved to write a novel
with an incident. Gosh!
Is it true that a folio periodical issued in Philadelphia is to have
a serial story entitled, “People Who Have Bored Me,” and that the
first chapters will be written by Mr. Howells, with comments on Scott,
Dickens, Thackeray, Dumas, Shakespeare, Moses, Phidias, the
critics of the daily papers and Henry Clay?
“Algernon wondered vaguely if he had done right in leaving the
handkerchief where she had dropped it, on the center table. If only it
had been the arm chair, now, what a different complexion it would
have put upon this dilemma—if it was a dilemma—no, hardly a
dilemma, rather a quandary, or even a question. And she—did she,
too, brood upon the handkerchief? Did she justify herself in dropping
it, in the way she did? He arose, wearily. ‘I dunno,’ he said, defiantly,
yet hopelessly, and sat down.”—Advance sheets from H. James.
That the Stage has fallen into a very bad way none dispute, and
under present conditions I cannot do better than to commend this
ordinance, passed in London in 1642, to the earnest consideration of
His Honor, the Mayor, and the Honorable Common Council of the
City of New York:

Whereas the Acts of Stage-Plays, Interludes and Common


Plays, Condemned by Ancient Heathens, and much less to be
tolerated amongst Professors of the Christian Religion, is the
occasion of many and sundry great vices and disorders,
tending to the high provocation of God’s wrath and
displeasure, and to the disturbance of the peace:
Therefore, for the better suppression of the said Stage-
Plays, Interludes, and Common Plays, It is Ordered and
Ordained by the Lords and Commons in this present
Parliament Assembled, and by Authority of the same, That all
Stage-Players, and Players of Interludes, and common Plays,
are hereby declared to be Rogues, and punishable, within the
Statutes of the thirty-ninth year of the Reign of Queen
Elizabeth, and the seventh year of the Reign of King James,
and liable unto the pains and penalties therein contained, and
proscribed against according to the said Statutes.
And it is further Ordered and Ordained by the Authority
aforesaid, That the Lord Mayor, Justices of the peace, and
Sheriffs of the City of London and Westminster, and of the
Counties of Middlesex and Surrey, or any two or more of
them, shall, and may, and are hereby, Authorized and
required to pull down and demolish, or cause or procure to be
pulled down and demolished all Stage Galleries, Seats, and
Boxes, erected or used, or which shall be erected and used
for the acting or playing, or seeing acted or played, such
Stage-Plays, Interludes, and Plays aforesaid, within the said
City of London and Libertis thereof, and other places within
their respective jurisdictions; and all such common Players,
and Actors of such Plays and Interludes, or any one of them,
or by Oath of two Witnesses shall be proved before them to
have acted or played such Plays and Interludes as aforesaid
at any time thereafter, by their Warrant or Warrants under
their hands and seals, to cause to be apprehended, and
openly and publicly given forty lashes on the bare back,
during the time of the said Market, and also to cause such
Offenders to enter into Recognizance with two sufficient
Sureties never to act or play any Plays or Interludes any
more, and shall return in the said Recognizance, or
Recognizances, into the Sizes or Sessions to be then next
holden for the said Counties and Cities respectively. And in
case any such person or persons so convicted of the said
offense, shall after again offend in the same kind, that then
the said person or persons offending, shall be and is hereby
declared to be, and be taken as an Incorrigible Rogue, and
shall be punished and dealt with as an Incorrigible Rogue
ought to be. And it is hereby further Ordered and Ordained,
That all and every sum and sums of Money gathered,
Collected, and taken by any person or persons, of such
persons as shall come to see, and be Spectators of the said
Stage-Plays, and Interludes, shall be forfeited and paid unto
the Church-Wardens of the Church of the Parish.
The presciences of the Seventeenth Century often held
morning conversazioni, receiving their callers in bed. Like cyclones,
fashions have a spiral movement; and now the good old custom of
the presciences has returned, and like the cyclone, manifests itself in
the West: a Chicago woman giving a weekly “Thursday Morning.”
The bed on which the hostess languishes is a Louis the Fourteen
Times—a gigantic four poster, with curtains partially drawn. When
each caller is announced a thin blue-veined hand is held out from
behind the curtains, and visions of a snowy lace-trimmed, Marchale
Field night gown swim before his eyes as the thin hand is reverently
kissed. The room is dimly lighted, the air is heavy with strange
mysterious perfumes and all the conversation is held in undertone. It
may not be amiss to state also that the coverlet of the bed is a very
modern crazy quilt that has been duly certified to by a commission
de lunatico enquirendo.
Certainly the people of Boston are a generous folk: in their walk
and conversation they even add an R to “banana,” and spell “law”
with four letters when three suffice—for hoi polloi.
The pink tea for Authors was a pretty failure. A Fictionist
standing behind a teacup with a pink tidy on his chest and pink bows
on his legs is a depressive sight, everywhere but in Philadelphia. But
while five o’clock tea does not work, eleven o’clock beer is a roaring
success.

Little Journeys
SERIES FOR 1896

Little Journeys to the Homes of


American Authors.
The papers below specified were, with the exception of that
contributed by the editor, Mr. Hubbard, originally issued by the late
G. P. Putnam, in 1853, in a book entitled Homes of American
Authors. It is now nearly half a century since this series (which
won for itself at the time a very noteworthy prestige) was brought
before the public; and the present publishers feel that no apology
is needed in presenting to a new generation of American readers
papers of such distinctive biographical interest and literary value.

No. 1, Emerson, by Geo. W. Curtis.


” 2, Bryant, by Caroline M. Kirkland.
” 3, Prescott, by Geo. S. Hillard.
” 4, Lowell, by Charles F. Briggs.
” 5, Simms, by Wm. Cullen Bryant.
” 6, Walt Whitman, by Elbert Hubbard.
” 7, Hawthorne, by Geo. Wm. Curtis.
” 8, Audubon, by Parke Godwin.
” 9, Irving, by H. T. Tuckerman.
” 10, Longfellow, by Geo. Wm. Curtis.
” 11, Everett, by Geo. S. Hillard.
” 12, Bancroft, by Geo. W. Greene.

The above papers will form the series of Little Journeys for the
year 1896.
They will be issued monthly, beginning January, 1896, in the
same general style as the series of 1895, at 50 cents a year, and
single copies will be sold for 5 cents, postage paid.
G. P. PUTNAM’S SONS,
NEW YORK AND LONDON

The ROYCROFT Printing Shop has


in preparation GLYNNE’S WIFE, a
story in verse by Mrs. Julia Ditto
Young.
Mrs. Young is a Poet who has written much but published little.
This, her latest and believed by her friends to be her best work, is
the product of a mind and heart singularly gifted by Nature, and
ripened by a long apprenticeship to Art. As a specimen of the pure
“lyric cry,” illustrating the melody possible in the English tongue,
the volume seems to stand alone among all books written by
modern versifiers. The delicacy of touch, the faultless rhythm, the
splendid vocabulary and the gentle tho’ sure insight into the
human heart, make a combination of qualities very, very seldom
seen. The author knows, and knowing blames not: a sustained
sympathy being the keynote of it all.
The publishers have endeavored to give the story a
typographical setting in keeping with the richness of the lines. Five
hundred and ninety copies are being printed on smooth Holland
hand-made paper, and twenty-five on Tokio Vellum. The copies on
Holland paper will be bound in boards covered with antique
watered silk; the Vellum copies are bound in like manner save that
each will bear on the cover a special water-color design done by
the hand of the author.
The price of the five hundred and ninety copies is two dollars
each; the Vellum copies five dollars each. Every copy will be
numbered and signed by Mrs. Young. Orders are now being
recorded and will be delivered on September 1st, numbered in the
order received.
THE ROYCROFT PRINTING SHOP,
East Aurora, New York.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookultra.com

You might also like