home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
The Datafile PD-CD 5
/
DATAFILE_PDCD5.iso
/
utilities
/
p
/
python
/
!ibrowse
/
files
/
pylibi-4
< prev
next >
Encoding:
Amiga
Atari
Commodore
DOS
FM Towns/JPY
Macintosh
Macintosh JP
Macintosh to JP
NeXTSTEP
RISC OS/Acorn
Shift JIS
UTF-8
Wrap
GNU Info File
|
1996-11-14
|
49.7 KB
|
1,339 lines
This is Info file pylibi, produced by Makeinfo-1.55 from the input file
lib.texi.
This file describes the built-in types, exceptions and functions and the
standard modules that come with the Python system. It assumes basic
knowledge about the Python language. For an informal introduction to
the language, see the Python Tutorial. The Python Reference Manual
gives a more formal definition of the language. (These manuals are not
yet available in INFO or Texinfo format.)
Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, The
Netherlands.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI or Corporation for National Research Initiatives or CNRI
not be used in advertising or publicity pertaining to distribution of
the software without specific, written prior permission.
While CWI is the initial source for this software, a modified version
is made available by the Corporation for National Research Initiatives
(CNRI) at the Internet address ftp://ftp.python.org.
STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
File: pylibi, Node: os, Next: time, Prev: Generic Operating System Services, Up: Generic Operating System Services
Standard Module `os'
====================
This module provides a more portable way of using operating system (OS)
dependent functionality than importing an OS dependent built-in module
like `posix'.
When the optional built-in module `posix' is available, this module
exports the same functions and data as `posix'; otherwise, it searches
for an OS dependent built-in module like `mac' and exports the same
functions and data as found there. The design of all Python's built-in
OS dependent modules is such that as long as the same functionality is
available, it uses the same interface; e.g., the function
`os.stat(FILE)' returns stat info about a FILE in a format compatible
with the POSIX interface.
Extensions peculiar to a particular OS are also available through the
`os' module, but using them is of course a threat to portability!
Note that after the first time `os' is imported, there is *no*
performance penalty in using functions from `os' instead of directly
from the OS dependent built-in module, so there should be *no* reason
not to use `os'!
In addition to whatever the correct OS dependent module exports, the
following variables and functions are always exported by `os':
- data of module os: name
The name of the OS dependent module imported. The following names
have currently been registered: `'posix'', `'nt'', `'dos'',
`'mac''.
- data of module os: path
The corresponding OS dependent standard module for pathname
operations, e.g., `posixpath' or `macpath'. Thus, (given the
proper imports), `os.path.split(FILE)' is equivalent to but more
portable than `posixpath.split(FILE)'.
- data of module os: curdir
The constant string used by the OS to refer to the current
directory, e.g. `'.'' for POSIX or `':'' for the Mac.
- data of module os: pardir
The constant string used by the OS to refer to the parent
directory, e.g. `'..'' for POSIX or `'::'' for the Mac.
- data of module os: sep
The character used by the OS to separate pathname components, e.g.
`'/'' for POSIX or `':'' for the Mac. Note that knowing this is
not sufficient to be able to parse or concatenate pathnames--better
use `os.path.split()' and `os.path.join()'--but it is occasionally
useful.
- data of module os: pathsep
The character conventionally used by the OS to separate search
patch components (as in `$PATH'), e.g. `':'' for POSIX or `';''
for MS-DOS.
- data of module os: defpath
The default search path used by `os.exec*p*()' if the environment
doesn't have a `'PATH'' key.
- function of module os: execl (PATH, ARG0, ARG1, ...)
This is equivalent to `os.execv(PATH, (ARG0, ARG1, ...))'.
- function of module os: execle (PATH, ARG0, ARG1, ..., ENV)
This is equivalent to `os.execve(PATH, (ARG0, ARG1, ...), ENV)'.
- function of module os: execlp (PATH, ARG0, ARG1, ...)
This is equivalent to `os.execvp(PATH, (ARG0, ARG1, ...))'.
- function of module os: execvp (PATH, ARGS)
This is like `os.execv(PATH, ARGS)' but duplicates the shell's
actions in searching for an executable file in a list of
directories. The directory list is obtained from
`os.environ['PATH']'.
- function of module os: execvpe (PATH, ARGS, ENV)
This is a cross between `os.execve()' and `os.execvp()'. The
directory list is obtained from `ENV['PATH']'.
(The functions `os.execv()' and `execve()' are not documented here,
since they are implemented by the OS dependent module. If the OS
dependent module doesn't define either of these, the functions that
rely on it will raise an exception. They are documented in the section
on module `posix', together with all other functions that `os' imports
from the OS dependent module.)
File: pylibi, Node: time, Next: getopt, Prev: os, Up: Generic Operating System Services
Built-in Module `time'
======================
This module provides various time-related functions. It is always
available.
An explanation of some terminology and conventions is in order.
* The "epoch" is the point where the time starts. On January 1st of
that year, at 0 hours, the "time since the epoch" is zero. For
UNIX, the epoch is 1970. To find out what the epoch is, look at
`gmtime(0)'.
* UTC is Coordinated Universal Time (formerly known as Greenwich Mean
Time). The acronym UTC is not a mistake but a compromise between
English and French.
* DST is Daylight Saving Time, an adjustment of the timezone by
(usually) one hour during part of the year. DST rules are magic
(determined by local law) and can change from year to year. The C
library has a table containing the local rules (often it is read
from a system file for flexibility) and is the only source of True
Wisdom in this respect.
* The precision of the various real-time functions may be less than
suggested by the units in which their value or argument is
expressed. E.g. on most UNIX systems, the clock "ticks" only 50
or 100 times a second, and on the Mac, times are only accurate to
whole seconds.
* The time tuple as returned by `gmtime()' and `localtime()', or as
accpted by `mktime()' is a tuple of 9 integers: year (e.g. 1993),
month (1-12), day (1-31), hour (0-23), minute (0-59), second
(0-59), weekday (0-6, monday is 0), Julian day (1-366) and
daylight savings flag (-1, 0 or 1). Note that unlike the C
structure, the month value is a range of 1-12, not 0-11. A year
value of 100 will typically be silently converted to 1900 year
value. A -1 argument as daylight savings flag, passed to
`mktime()' will usually result in the correct daylight savings
state to be filled in.
The module defines the following functions and data items:
- data of module time: altzone
The offset of the local DST timezone, in seconds west of the 0th
meridian, if one is defined. Negative if the local DST timezone is
east of the 0th meridian (as in Western Europe, including the UK).
Only use this if `daylight' is nonzero.
- function of module time: asctime (TUPLE)
Convert a tuple representing a time as returned by `gmtime()' or
`localtime()' to a 24-character string of the following form:
`'Sun Jun 20 23:21:05 1993''. Note: unlike the C function of the
same name, there is no trailing newline.
- function of module time: clock ()
Return the current CPU time as a floating point number expressed in
seconds. The precision, and in fact the very definiton of the
meaning of "CPU time", depends on that of the C function of the
same name.
- function of module time: ctime (SECS)
Convert a time expressed in seconds since the epoch to a string
representing local time. `ctime(t)' is equivalent to
`asctime(localtime(t))'.
- data of module time: daylight
Nonzero if a DST timezone is defined.
- function of module time: gmtime (SECS)
Convert a time expressed in seconds since the epoch to a time tuple
in UTC in which the dst flag is always zero. Fractions of a
second are ignored.
- function of module time: localtime (SECS)
Like `gmtime' but converts to local time. The dst flag is set to
1 when DST applies to the given time.
- function of module time: mktime (TUPLE)
This is the inverse function of `localtime'. Its argument is the
full 9-tuple (since the dst flag is needed -- pass -1 as the dst
flag if it is unknown) which expresses the time in local time, not
UTC. It returns a floating point number, for compatibility with
`time.time()'. If the input value can't be represented as a valid
time, OverflowError is raised.
- function of module time: sleep (SECS)
Suspend execution for the given number of seconds. The argument
may be a floating point number to indicate a more precise sleep
time.
- function of module time: strftime (FORMAT, TUPLE)
Convert a tuple representing a time as returned by `gmtime()' or
`localtime()' to a string as specified by the format argument.
The following directives, shown without the optional field width
and precision specification, are replaced by the indicated
characters:
lp25em %a & Locale's abbreviated weekday name.
%A & Locale's full weekday name.
%b & Locale's abbreviated month name.
%B & Locale's full month name.
%c & Locale's appropriate date and time representation.
%d & Day of the month as a decimal number [01,31].
%E & Locale's combined Emperor/Era name and year.
%H & Hour (24-hour clock) as a decimal number [00,23].
%I & Hour (12-hour clock) as a decimal number [01,12].
%j & Day of the year as a decimal number [001,366].
%m & Month as a decimal number [01,12].
%M & Minute as a decimal number [00,59].
%n & New-line character.
%N & Locale's Emperor/Era name.
%o & Locale's Emperor/Era year.
%p & Locale's equivalent of either AM or PM.
%S & Second as a decimal number [00,61].
%t & Tab character.
%U & Week number of the year (Sunday as the first day of the
week) as a decimal number [00,53]. All days in a new year
preceding the first Sunday are considered to be in week 0.
%w & Weekday as a decimal number [0(Sunday),6].
%W & Week number of the year (Monday as the first day of the
week) as a decimal number [00,53]. All days in a new year
preceding the first Sunday are considered to be in week 0.
%x & Locale's appropriate date representation.
%X & Locale's appropriate time representation.
%y & Year without century as a decimal number [00,99].
%Y & Year with century as a decimal number.
%Z & Time zone name (or by no characters if no time zone
exists).
%% & %
An optional field width and precision specification can immediately
follow the initial % of a directive in the following order:
lp25em [-|0]w & the decimal digit string w specifies a
minimum field width in which the result of the conversion is right-
or left-justified. It is right-justified (with space padding) by
default. If the optional flag `-' is specified, it is
left-justified with space padding on the right. If the optional
flag `0' is specified, it is right-justified and padded with zeros
on the left.
.p & the decimal digit string p specifies the minimum
number of digits to appear for the d, H, I, j, m, M, o, S, U, w,
W, y and Y directives, and the maximum number of characters to be
used from the a, A, b, B, c, D, E, F, h, n, N, p, r, t, T, x, X,
z, Z, and the first case, if a directive supplies fewer digits
than specified by the precision, it will be expanded with leading
zeros. In the second case, if a directive supplies more
characters than specified by the precision, excess characters will
truncated on the right.
If no field width or precision is specified for a d, H, I, m, M,
S, U, W, y, or j directive, a default of .2 is used for all but j
for which .3 is used.
- function of module time: time ()
Return the time as a floating point number expressed in seconds
since the epoch, in UTC. Note that even though the time is always
returned as a floating point number, not all systems provide time
with a better precision than 1 second.
- data of module time: timezone
The offset of the local (non-DST) timezone, in seconds west of the
0th meridian (i.e. negative in most of Western Europe, positive in
the US, zero in the UK).
- data of module time: tzname
A tuple of two strings: the first is the name of the local non-DST
timezone, the second is the name of the local DST timezone. If no
DST timezone is defined, the second string should not be used.
File: pylibi, Node: getopt, Next: tempfile, Prev: time, Up: Generic Operating System Services
Standard Module `getopt'
========================
This module helps scripts to parse the command line arguments in
`sys.argv'. It supports the same conventions as the UNIX `getopt()'
function (including the special meanings of arguments of the form `-'
and `--'). Long options similar to those supported by GNU software may
be used as well via an optional third argument. It defines the function
`getopt.getopt(args, options [, long_options])' and the exception
`getopt.error'.
The first argument to `getopt()' is the argument list passed to the
script with its first element chopped off (i.e., `sys.argv[1:]'). The
second argument is the string of option letters that the script wants
to recognize, with options that require an argument followed by a colon
(i.e., the same format that UNIX `getopt()' uses). The third option,
if specified, is a list of strings with the names of the long options
which should be supported. The leading `'--'' characters should not be
included in the option name. Options which require an argument should
be followed by an equal sign (`'=''). The return value consists of two
elements: the first is a list of option-and-value pairs; the second is
the list of program arguments left after the option list was stripped
(this is a trailing slice of the first argument). Each
option-and-value pair returned has the option as its first element,
prefixed with a hyphen (e.g., `'-x''), and the option argument as its
second element, or an empty string if the option has no argument. The
options occur in the list in the same order in which they were found,
thus allowing multiple occurrences. Long and short options may be
mixed.
An example using only UNIX style options:
>>> import getopt, string
>>> args = string.split('-a -b -cfoo -d bar a1 a2')
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
>>>
Using long option names is equally easy:
>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = string.split(s)
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
... 'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
>>> args
['a1', 'a2']
>>>
The exception `getopt.error = 'getopt.error'' is raised when an
unrecognized option is found in the argument list or when an option
requiring an argument is given none. The argument to the exception is
a string indicating the cause of the error. For long options, an
argument given to an option which does not require one will also cause
this exception to be raised.
File: pylibi, Node: tempfile, Next: errno, Prev: getopt, Up: Generic Operating System Services
Standard Module `tempfile'
==========================
This module generates temporary file names. It is not UNIX specific,
but it may require some help on non-UNIX systems.
Note: the modules does not create temporary files, nor does it
automatically remove them when the current process exits or dies.
The module defines a single user-callable function:
- function of module tempfile: mktemp ()
Return a unique temporary filename. This is an absolute pathname
of a file that does not exist at the time the call is made. No
two calls will return the same filename.
The module uses two global variables that tell it how to construct a
temporary name. The caller may assign values to them; by default they
are initialized at the first call to `mktemp()'.
- data of module tempfile: tempdir
When set to a value other than `None', this variable defines the
directory in which filenames returned by `mktemp()' reside. The
default is taken from the environment variable `TMPDIR'; if this
is not set, either `/usr/tmp' is used (on UNIX), or the current
working directory (all other systems). No check is made to see
whether its value is valid.
- data of module tempfile: template
When set to a value other than `None', this variable defines the
prefix of the final component of the filenames returned by
`mktemp()'. A string of decimal digits is added to generate
unique filenames. The default is either "`@PID.'" where PID is
the current process ID (on UNIX), or "`tmp'" (all other systems).
Warning: if a UNIX process uses `mktemp()', then calls `fork()' and
both parent and child continue to use `mktemp()', the processes will
generate conflicting temporary names. To resolve this, the child
process should assign `None' to `template', to force recomputing the
default on the next call to `mktemp()'.
File: pylibi, Node: errno, Prev: tempfile, Up: Generic Operating System Services
Standard Module `errno'
=======================
This module makes available standard errno system symbols. The value
of each symbol is the corresponding integer value. The names and
descriptions are borrowed from linux/include/errno.h, which should be
pretty all-inclusive. Of the following list, symbols that are not used
on the current platform are not defined by the module.
Symbols available can include:
- data of module errno: EPERM
Operation not permitted
- data of module errno: ENOENT
No such file or directory
- data of module errno: ESRCH
No such process
- data of module errno: EINTR
Interrupted system call
- data of module errno: EIO
I/O error
- data of module errno: ENXIO
No such device or address
- data of module errno: E2BIG
Arg list too long
- data of module errno: ENOEXEC
Exec format error
- data of module errno: EBADF
Bad file number
- data of module errno: ECHILD
No child processes
- data of module errno: EAGAIN
Try again
- data of module errno: ENOMEM
Out of memory
- data of module errno: EACCES
Permission denied
- data of module errno: EFAULT
Bad address
- data of module errno: ENOTBLK
Block device required
- data of module errno: EBUSY
Device or resource busy
- data of module errno: EEXIST
File exists
- data of module errno: EXDEV
Cross-device link
- data of module errno: ENODEV
No such device
- data of module errno: ENOTDIR
Not a directory
- data of module errno: EISDIR
Is a directory
- data of module errno: EINVAL
Invalid argument
- data of module errno: ENFILE
File table overflow
- data of module errno: EMFILE
Too many open files
- data of module errno: ENOTTY
Not a typewriter
- data of module errno: ETXTBSY
Text file busy
- data of module errno: EFBIG
File too large
- data of module errno: ENOSPC
No space left on device
- data of module errno: ESPIPE
Illegal seek
- data of module errno: EROFS
Read-only file system
- data of module errno: EMLINK
Too many links
- data of module errno: EPIPE
Broken pipe
- data of module errno: EDOM
Math argument out of domain of func
- data of module errno: ERANGE
Math result not representable
- data of module errno: EDEADLK
Resource deadlock would occur
- data of module errno: ENAMETOOLONG
File name too long
- data of module errno: ENOLCK
No record locks available
- data of module errno: ENOSYS
Function not implemented
- data of module errno: ENOTEMPTY
Directory not empty
- data of module errno: ELOOP
Too many symbolic links encountered
- data of module errno: EWOULDBLOCK
Operation would block
- data of module errno: ENOMSG
No message of desired type
- data of module errno: EIDRM
Identifier removed
- data of module errno: ECHRNG
Channel number out of range
- data of module errno: EL2NSYNC
Level 2 not synchronized
- data of module errno: EL3HLT
Level 3 halted
- data of module errno: EL3RST
Level 3 reset
- data of module errno: ELNRNG
Link number out of range
- data of module errno: EUNATCH
Protocol driver not attached
- data of module errno: ENOCSI
No CSI structure available
- data of module errno: EL2HLT
Level 2 halted
- data of module errno: EBADE
Invalid exchange
- data of module errno: EBADR
Invalid request descriptor
- data of module errno: EXFULL
Exchange full
- data of module errno: ENOANO
No anode
- data of module errno: EBADRQC
Invalid request code
- data of module errno: EBADSLT
Invalid slot
- data of module errno: EDEADLOCK
File locking deadlock error
- data of module errno: EBFONT
Bad font file format
- data of module errno: ENOSTR
Device not a stream
- data of module errno: ENODATA
No data available
- data of module errno: ETIME
Timer expired
- data of module errno: ENOSR
Out of streams resources
- data of module errno: ENONET
Machine is not on the network
- data of module errno: ENOPKG
Package not installed
- data of module errno: EREMOTE
Object is remote
- data of module errno: ENOLINK
Link has been severed
- data of module errno: EADV
Advertise error
- data of module errno: ESRMNT
Srmount error
- data of module errno: ECOMM
Communication error on send
- data of module errno: EPROTO
Protocol error
- data of module errno: EMULTIHOP
Multihop attempted
- data of module errno: EDOTDOT
RFS specific error
- data of module errno: EBADMSG
Not a data message
- data of module errno: EOVERFLOW
Value too large for defined data type
- data of module errno: ENOTUNIQ
Name not unique on network
- data of module errno: EBADFD
File descriptor in bad state
- data of module errno: EREMCHG
Remote address changed
- data of module errno: ELIBACC
Can not access a needed shared library
- data of module errno: ELIBBAD
Accessing a corrupted shared library
- data of module errno: ELIBSCN
.lib section in a.out corrupted
- data of module errno: ELIBMAX
Attempting to link in too many shared libraries
- data of module errno: ELIBEXEC
Cannot exec a shared library directly
- data of module errno: EILSEQ
Illegal byte sequence
- data of module errno: ERESTART
Interrupted system call should be restarted
- data of module errno: ESTRPIPE
Streams pipe error
- data of module errno: EUSERS
Too many users
- data of module errno: ENOTSOCK
Socket operation on non-socket
- data of module errno: EDESTADDRREQ
Destination address required
- data of module errno: EMSGSIZE
Message too long
- data of module errno: EPROTOTYPE
Protocol wrong type for socket
- data of module errno: ENOPROTOOPT
Protocol not available
- data of module errno: EPROTONOSUPPORT
Protocol not supported
- data of module errno: ESOCKTNOSUPPORT
Socket type not supported
- data of module errno: EOPNOTSUPP
Operation not supported on transport endpoint
- data of module errno: EPFNOSUPPORT
Protocol family not supported
- data of module errno: EAFNOSUPPORT
Address family not supported by protocol
- data of module errno: EADDRINUSE
Address already in use
- data of module errno: EADDRNOTAVAIL
Cannot assign requested address
- data of module errno: ENETDOWN
Network is down
- data of module errno: ENETUNREACH
Network is unreachable
- data of module errno: ENETRESET
Network dropped connection because of reset
- data of module errno: ECONNABORTED
Software caused connection abort
- data of module errno: ECONNRESET
Connection reset by peer
- data of module errno: ENOBUFS
No buffer space available
- data of module errno: EISCONN
Transport endpoint is already connected
- data of module errno: ENOTCONN
Transport endpoint is not connected
- data of module errno: ESHUTDOWN
Cannot send after transport endpoint shutdown
- data of module errno: ETOOMANYREFS
Too many references: cannot splice
- data of module errno: ETIMEDOUT
Connection timed out
- data of module errno: ECONNREFUSED
Connection refused
- data of module errno: EHOSTDOWN
Host is down
- data of module errno: EHOSTUNREACH
No route to host
- data of module errno: EALREADY
Operation already in progress
- data of module errno: EINPROGRESS
Operation now in progress
- data of module errno: ESTALE
Stale NFS file handle
- data of module errno: EUCLEAN
Structure needs cleaning
- data of module errno: ENOTNAM
Not a XENIX named type file
- data of module errno: ENAVAIL
No XENIX semaphores available
- data of module errno: EISNAM
Is a named type file
- data of module errno: EREMOTEIO
Remote I/O error
- data of module errno: EDQUOT
Quota exceeded
File: pylibi, Node: Optional Operating System Services, Next: The Python Debugger, Prev: Generic Operating System Services, Up: Top
Optional Operating System Services
**********************************
The modules described in this chapter provide interfaces to operating
system features that are available on selected operating systems only.
The interfaces are generally modelled after the UNIX or C interfaces
but they are available on some other systems as well (e.g. Windows or
NT). Here's an overview:
signal
-- Set handlers for asynchronous events.
socket
-- Low-level networking interface.
select
-- Wait for I/O completion on multiple streams.
thread
-- Create multiple threads of control within one namespace.
* Menu:
* signal::
* socket::
File: pylibi, Node: signal, Next: socket, Prev: Optional Operating System Services, Up: Optional Operating System Services
Built-in Module `signal'
========================
This module provides mechanisms to use signal handlers in Python. Some
general rules for working with signals handlers:
* A handler for a particular signal, once set, remains installed
until it is explicitly reset (i.e. Python emulates the BSD style
interface regardless of the underlying implementation), with the
exception of the handler for `SIGCHLD', which follows the
underlying implementation.
* There is no way to "block" signals temporarily from critical
sections (since this is not supported by all UNIX flavors).
* Although Python signal handlers are called asynchronously as far as
the Python user is concerned, they can only occur between the
"atomic" instructions of the Python interpreter. This means that
signals arriving during long calculations implemented purely in C
(e.g. regular expression matches on large bodies of text) may be
delayed for an arbitrary amount of time.
* When a signal arrives during an I/O operation, it is possible that
the I/O operation raises an exception after the signal handler
returns. This is dependent on the underlying UNIX system's
semantics regarding interrupted system calls.
* Because the C signal handler always returns, it makes little sense
to catch synchronous errors like `SIGFPE' or `SIGSEGV'.
* Python installs a small number of signal handlers by default:
`SIGPIPE' is ignored (so write errors on pipes and sockets can be
reported as ordinary Python exceptions), `SIGINT' is translated
into a `KeyboardInterrupt' exception, and `SIGTERM' is caught so
that necessary cleanup (especially `sys.exitfunc') can be
performed before actually terminating. All of these can be
overridden.
* Some care must be taken if both signals and threads are used in the
same program. The fundamental thing to remember in using signals
and threads simultaneously is: always perform `signal()' operations
in the main thread of execution. Any thread can perform an
`alarm()', `getsignal()', or `pause()'; only the main thread can
set a new signal handler, and the main thread will be the only one
to receive signals (this is enforced by the Python signal module,
even if the underlying thread implementation supports sending
signals to individual threads). This means that signals can't be
used as a means of interthread communication. Use locks instead.
The variables defined in the signal module are:
- data of module signal: SIG_DFL
This is one of two standard signal handling options; it will simply
perform the default function for the signal. For example, on most
systems the default action for SIGQUIT is to dump core and exit,
while the default action for SIGCLD is to simply ignore it.
- data of module signal: SIG_IGN
This is another standard signal handler, which will simply ignore
the given signal.
- data of module signal: SIG*
All the signal numbers are defined symbolically. For example, the
hangup signal is defined as `signal.SIGHUP'; the variable names
are identical to the names used in C programs, as found in
`signal.h'. The UNIX man page for `signal' lists the existing
signals (on some systems this is `signal(2)', on others the list
is in `signal(7)'). Note that not all systems define the same set
of signal names; only those names defined by the system are
defined by this module.
- data of module signal: NSIG
One more than the number of the highest signal number.
The signal module defines the following functions:
- function of module signal: alarm (TIME)
If TIME is non-zero, this function requests that a `SIGALRM'
signal be sent to the process in TIME seconds. Any previously
scheduled alarm is canceled (i.e. only one alarm can be scheduled
at any time). The returned value is then the number of seconds
before any previously set alarm was to have been delivered. If
TIME is zero, no alarm id scheduled, and any scheduled alarm is
canceled. The return value is the number of seconds remaining
before a previously scheduled alarm. If the return value is zero,
no alarm is currently scheduled. (See the UNIX man page
`alarm(2)'.)
- function of module signal: getsignal (SIGNALNUM)
Return the current signal handler for the signal SIGNALNUM. The
returned value may be a callable Python object, or one of the
special values `signal.SIG_IGN', `signal.SIG_DFL' or `None'.
Here, `signal.SIG_IGN' means that the signal was previously
ignored, `signal.SIG_DFL' means that the default way of handling
the signal was previously in use, and `None' means that the
previous signal handler was not installed from Python.
- function of module signal: pause ()
Cause the process to sleep until a signal is received; the
appropriate handler will then be called. Returns nothing. (See
the UNIX man page `signal(2)'.)
- function of module signal: signal (SIGNALNUM, HANDLER)
Set the handler for signal SIGNALNUM to the function HANDLER.
hANDLER can be any callable Python object, or one of the special
values `signal.SIG_IGN' or `signal.SIG_DFL'. The previous signal
handler will be returned (see the description of `getsignal()'
above). (See the UNIX man page `signal(2)'.)
When threads are enabled, this function can only be called from the
main thread; attempting to call it from other threads will cause a
`ValueError' exception to be raised.
The HANDLER is called with two arguments: the signal number and
the current stack frame (`None' or a frame object; see the
reference manual for a description of frame objects).
File: pylibi, Node: socket, Prev: signal, Up: Optional Operating System Services
Built-in Module `socket'
========================
This module provides access to the BSD *socket* interface. It is
available on UNIX systems that support this interface.
For an introduction to socket programming (in C), see the following
papers: *An Introductory 4.3BSD Interprocess Communication Tutorial*,
by Stuart Sechrest and *An Advanced 4.3BSD Interprocess Communication
Tutorial*, by Samuel J. Leffler et al, both in the UNIX Programmer's
Manual, Supplementary Documents 1 (sections PS1:7 and PS1:8). The UNIX
manual pages for the various socket-related system calls are also a
valuable source of information on the details of socket semantics.
The Python interface is a straightforward transliteration of the UNIX
system call and library interface for sockets to Python's
object-oriented style: the `socket()' function returns a "socket
object" whose methods implement the various socket system calls.
Parameter types are somewhat higer-level than in the C interface: as
with `read()' and `write()' operations on Python files, buffer
allocation on receive operations is automatic, and buffer length is
implicit on send operations.
Socket addresses are represented as a single string for the `AF_UNIX'
address family and as a pair `(HOST, PORT)' for the `AF_INET' address
family, where HOST is a string representing either a hostname in
Internet domain notation like `'daring.cwi.nl'' or an IP address like
`'100.50.200.5'', and PORT is an integral port number. Other address
families are currently not supported. The address format required by a
particular socket object is automatically selected based on the address
family specified when the socket object was created.
All errors raise exceptions. The normal exceptions for invalid
argument types and out-of-memory conditions can be raised; errors
related to socket or address semantics raise the error `socket.error'.
Non-blocking mode is supported through the `setblocking()' method.
The module `socket' exports the following constants and functions:
- exception of module socket: error
This exception is raised for socket- or address-related errors.
The accompanying value is either a string telling what went wrong
or a pair `(ERRNO, STRING)' representing an error returned by a
system call, similar to the value accompanying `posix.error'.
- data of module socket: AF_UNIX
- data of module socket: AF_INET
These constants represent the address (and protocol) families,
used for the first argument to `socket()'. If the `AF_UNIX'
constant is not defined then this protocol is unsupported.
- data of module socket: SOCK_STREAM
- data of module socket: SOCK_DGRAM
- data of module socket: SOCK_RAW
- data of module socket: SOCK_RDM
- data of module socket: SOCK_SEQPACKET
These constants represent the socket types, used for the second
argument to `socket()'. (Only `SOCK_STREAM' and `SOCK_DGRAM'
appear to be generally useful.)
- data of module socket: SO_*
- data of module socket: SOMAXCONN
- data of module socket: MSG_*
- data of module socket: SOL_*
- data of module socket: IPPROTO_*
- data of module socket: IPPORT_*
- data of module socket: INADDR_*
- data of module socket: IP_*
Many constants of these forms, documented in the UNIX
documentation on sockets and/or the IP protocol, are also defined
in the socket module. They are generally used in arguments to the
`setsockopt' and `getsockopt' methods of socket objects. In most
cases, only those symbols that are defined in the UNIX header
files are defined; for a few symbols, default values are provided.
- function of module socket: gethostbyname (HOSTNAME)
Translate a host name to IP address format. The IP address is
returned as a string, e.g., `'100.50.200.5''. If the host name
is an IP address itself it is returned unchanged.
- function of module socket: gethostname ()
Return a string containing the hostname of the machine where the
Python interpreter is currently executing. If you want to know the
current machine's IP address, use
`socket.gethostbyname(socket.gethostname())'.
- function of module socket: gethostbyaddr (IP_ADDRESS)
Return a triple `(hostname, aliaslist, ipaddrlist)' where
`hostname' is the primary host name responding to the given
IP_ADDRESS, `aliaslist' is a (possibly empty) list of alternative
host names for the same address, and `ipaddrlist' is a list of IP
addresses for the same interface on the same host (most likely
containing only a single address).
- function of module socket: getservbyname (SERVICENAME, PROTOCOLNAME)
Translate an Internet service name and protocol name to a port
number for that service. The protocol name should be `'tcp'' or
`'udp''.
- function of module socket: socket (FAMILY, TYPE[, PROTO])
Create a new socket using the given address family, socket type and
protocol number. The address family should be `AF_INET' or
`AF_UNIX'. The socket type should be `SOCK_STREAM', `SOCK_DGRAM'
or perhaps one of the other `SOCK_' constants. The protocol
number is usually zero and may be omitted in that case.
- function of module socket: fromfd (FD, FAMILY, TYPE[, PROTO])
Build a socket object from an existing file descriptor (an integer
as returned by a file object's `fileno' method). Address family,
socket type and protocol number are as for the `socket' function
above. The file descriptor should refer to a socket, but this is
not checked -- subsequent operations on the object may fail if the
file descriptor is invalid. This function is rarely needed, but
can be used to get or set socket options on a socket passed to a
program as standard input or output (e.g. a server started by the
UNIX inet daemon).
* Menu:
* Socket Objects::
* Socket Example::
File: pylibi, Node: Socket Objects, Next: Socket Example, Prev: socket, Up: socket
Socket Objects
--------------
Socket objects have the following methods. Except for `makefile()'
these correspond to UNIX system calls applicable to sockets.
- Method on socket: accept ()
Accept a connection. The socket must be bound to an address and
listening for connections. The return value is a pair `(CONN,
ADDRESS)' where CONN is a *new* socket object usable to send and
receive data on the connection, and ADDRESS is the address bound
to the socket on the other end of the connection.
- Method on socket: bind (ADDRESS)
Bind the socket to ADDRESS. The socket must not already be bound.
(The format of ADDRESS depends on the address family -- see above.)
- Method on socket: close ()
Close the socket. All future operations on the socket object will
fail. The remote end will receive no more data (after queued data
is flushed). Sockets are automatically closed when they are
garbage-collected.
- Method on socket: connect (ADDRESS)
Connect to a remote socket at ADDRESS. (The format of ADDRESS
depends on the address family -- see above.)
- Method on socket: fileno ()
Return the socket's file descriptor (a small integer). This is
useful with `select'.
- Method on socket: getpeername ()
Return the remote address to which the socket is connected. This
is useful to find out the port number of a remote IP socket, for
instance. (The format of the address returned depends on the
address family -- see above.) On some systems this function is
not supported.
- Method on socket: getsockname ()
Return the socket's own address. This is useful to find out the
port number of an IP socket, for instance. (The format of the
address returned depends on the address family -- see above.)
- Method on socket: getsockopt (LEVEL, OPTNAME[, BUFLEN])
Return the value of the given socket option (see the UNIX man page
getsockopt(2)). The needed symbolic constants (`SO_*' etc.) are
defined in this module. If BUFLEN is absent, an integer option is
assumed and its integer value is returned by the function. If
BUFLEN is present, it specifies the maximum length of the buffer
used to receive the option in, and this buffer is returned as a
string. It is up to the caller to decode the contents of the
buffer (see the optional built-in module `struct' for a way to
decode C structures encoded as strings).
- Method on socket: listen (BACKLOG)
Listen for connections made to the socket. The BACKLOG argument
specifies the maximum number of queued connections and should be at
least 1; the maximum value is system-dependent (usually 5).
- Method on socket: makefile ([MODE[, BUFSIZE]])
Return a "file object" associated with the socket. (File objects
were described earlier under Built-in Types.) The file object
references a `dup()'ped version of the socket file descriptor, so
the file object and socket object may be closed or
garbage-collected independently. The optional MODE and BUFSIZE
arguments are interpreted the same way as by the built-in `open()'
function.
- Method on socket: recv (BUFSIZE[, FLAGS])
Receive data from the socket. The return value is a string
representing the data received. The maximum amount of data to be
received at once is specified by BUFSIZE. See the UNIX manual page
for the meaning of the optional argument FLAGS; it defaults to
zero.
- Method on socket: recvfrom (BUFSIZE[, FLAGS])
Receive data from the socket. The return value is a pair
`(STRING, ADDRESS)' where STRING is a string representing the data
received and ADDRESS is the address of the socket sending the
data. The optional FLAGS argument has the same meaning as for
`recv()' above. (The format of ADDRESS depends on the address
family -- see above.)
- Method on socket: send (STRING[, FLAGS])
Send data to the socket. The socket must be connected to a remote
socket. The optional FLAGS argument has the same meaning as for
`recv()' above. Return the number of bytes sent.
- Method on socket: sendto (STRING[, FLAGS], ADDRESS)
Send data to the socket. The socket should not be connected to a
remote socket, since the destination socket is specified by
`address'. The optional FLAGS argument has the same meaning as
for `recv()' above. Return the number of bytes sent. (The format
of ADDRESS depends on the address family -- see above.)
- Method on socket: setblocking (FLAG)
Set blocking or non-blocking mode of the socket: if FLAG is 0, the
socket is set to non-blocking, else to blocking mode. Initially
all sockets are in blocking mode. In non-blocking mode, if a
`recv' call doesn't find any data, or if a `send' call can't
immediately dispose of the data, a `socket.error' exception is
raised; in blocking mode, the calls block until they can proceed.
- Method on socket: setsockopt (LEVEL, OPTNAME, VALUE)
Set the value of the given socket option (see the UNIX man page
setsockopt(2)). The needed symbolic constants are defined in the
`socket' module (`SO_*' etc.). The value can be an integer or a
string representing a buffer. In the latter case it is up to the
caller to ensure that the string contains the proper bits (see the
optional built-in module `struct' for a way to encode C structures
as strings).
- Method on socket: shutdown (HOW)
Shut down one or both halves of the connection. If HOW is `0',
further receives are disallowed. If HOW is `1', further sends are
disallowed. If HOW is `2', further sends and receives are
disallowed.
Note that there are no methods `read()' or `write()'; use `recv()' and
`send()' without FLAGS argument instead.
File: pylibi, Node: Socket Example, Prev: Socket Objects, Up: socket
Example
-------
Here are two minimal example programs using the TCP/IP protocol: a
server that echoes all data that it receives back (servicing only one
client), and a client using it. Note that a server must perform the
sequence `socket', `bind', `listen', `accept' (possibly repeating the
`accept' to service more than one client), while a client only needs
the sequence `socket', `connect'. Also note that the server does not
`send'/`receive' on the socket it is listening on but on the new socket
returned by `accept'.
# Echo server program
from socket import *
HOST = '' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged server
s = socket(AF_INET, SOCK_STREAM)
s.bind(HOST, PORT)
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
# Echo client program
from socket import *
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket(AF_INET, SOCK_STREAM)
s.connect(HOST, PORT)
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', `data`
File: pylibi, Node: The Python Debugger, Next: The Python Profiler, Prev: Optional Operating System Services, Up: Top
The Python Debugger
*******************
The module `pdb' defines an interactive source code debugger for Python
programs. It supports setting breakpoints and single stepping at the
source line level, inspection of stack frames, source code listing, and
evaluation of arbitrary Python code in the context of any stack frame.
It also supports post-mortem debugging and can be called under program
control.
The debugger is extensible -- it is actually defined as a class `Pdb'.
This is currently undocumented but easily understood by reading the
source. The extension interface uses the (also undocumented) modules
`bdb' and `cmd'.
A primitive windowing version of the debugger also exists -- this is
module `wdb', which requires STDWIN (see the chapter on STDWIN specific
modules).
The debugger's prompt is "`(Pdb) '". Typical usage to run a program
under control of the debugger is:
>>> import pdb
>>> import mymodule
>>> pdb.run('mymodule.test()')
> <string>(0)?()
(Pdb) continue
> <string>(1)?()
(Pdb) continue
NameError: 'spam'
> <string>(1)?()
(Pdb)
Typical usage to inspect a crashed program is:
>>> import pdb
>>> import mymodule
>>> mymodule.test()
Traceback (innermost last):
File "<stdin>", line 1, in ?
File "./mymodule.py", line 4, in test
test2()
File "./mymodule.py", line 3, in test2
print spam
NameError: spam
>>> pdb.pm()
> ./mymodule.py(3)test2()
-> print spam
(Pdb)
The module defines the following functions; each enters the debugger in
a slightly different way:
- function of module pdb: run (STATEMENT[, GLOBALS[, LOCALS]])
Execute the STATEMENT (given as a string) under debugger control.
The debugger prompt appears before any code is executed; you can
set breakpoints and type `continue', or you can step through the
statement using `step' or `next' (all these commands are explained
below). The optional GLOBALS and LOCALS arguments specify the
environment in which the code is executed; by default the
dictionary of the module `__main__' is used. (See the explanation
of the `exec' statement or the `eval()' built-in function.)
- function of module pdb: runeval (EXPRESSION[, GLOBALS[, LOCALS]])
Evaluate the EXPRESSION (given as a a string) under debugger
control. When `runeval()' returns, it returns the value of the
expression. Otherwise this function is similar to `run()'.
- function of module pdb: runcall (FUNCTION[, ARGUMENT, ...])
Call the FUNCTION (a function or method object, not a string) with
the given arguments. When `runcall()' returns, it returns
whatever the function call returned. The debugger prompt appears
as soon as the function is entered.
- function of module pdb: set_trace ()
Enter the debugger at the calling stack frame. This is useful to
hard-code a breakpoint at a given point in a program, even if the
code is not otherwise being debugged (e.g. when an assertion
fails).
- function of module pdb: post_mortem (TRACEBACK)
Enter post-mortem debugging of the given TRACEBACK object.
- function of module pdb: pm ()
Enter post-mortem debugging of the traceback found in
`sys.last_traceback'.
* Menu:
* Debugger Commands::
* How It Works::