Python Standard Library Doc

Table of Contents

  • Ch 01 - 05
    • 01 Introduction
    • 02 Built-in Functions
      • Summary Table
      • a-e
      • e-g
      • h-i
      • l-o
      • p-r
      • s-z
    • 03 Non-essential Built-in Functions
    • 04 Built-in Constants
      • Constants added by the site module
    • 05 Built-in Types
      • 1. Truth Value Testing
      • 2. Boolean Operations — and, or, not
      • 3. Comparisons
      • 4. Numeric Types — int, float, long, complex
        • 4.1. Bitwise Operations on Integer Types
        • 4.2. Additional Methods on Integer Types
        • 4.3. Additional Methods on Float
      • 5. Iterator Types
        • 5.1. Generator Types
      • 6. Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange
        • 6.1. String Methods
        • 6.2. String Formatting Operations
        • 6.3. XRange Type
        • 6.4. Mutable Sequence Types
      • 7. Set Types — set, frozenset
      • 8. Mapping Types — dict
        • 8.1. Dictionary view objects
      • 9. File Objects
      • 10. memoryview type
      • 11. Context Manager Types
      • 12. Other Built-in Types
        • 12.1. Modules
        • 12.2. Classes and Class Instances
        • 12.3. Functions
        • 12.4. Methods
        • 12.5. Code Objects
        • 12.6. Type Objects
        • 12.7. The Null Object
        • 12.8. The Ellipsis Object
        • 12.9. The NotImplemented Object
        • 12.10. Boolean Values
        • 12.11. Internal Objects
      • 13. Special Attributes
  • Ch 06 - 10
    • 06 Built-in Exceptions
      • Exception hierarchy
    • 07. String Services
      • 1. string — Common string operations
        • 1.1. String constants
        • 1.2. Custom String Formatting
        • 1.3. Format String Syntax
          • 1.3.1. Format Specification Mini-Language
          • 1.3.2. Format examples
        • 1.4. Template strings
        • 1.5. String functions
        • 1.6. Deprecated string functions
      • 2. re — Regular expression operations
        • 2.1. Regular Expression Syntax
        • 2.2. Module Contents
        • 2.3. Regular Expression Objects
        • 2.4. Match Objects
        • 2.5. Examples
          • 2.5.1. Checking For a Pair
          • 2.5.2. Simulating scanf()
          • 2.5.3. search() vs. match()
          • 2.5.4. Making a Phonebook
          • 2.5.5. Text Munging
          • 2.5.6. Finding all Adverbs
          • 2.5.7. Finding all Adverbs and their Positions
          • 2.5.8. Raw String Notation
      • 3. struct — Interpret strings as packed binary data
        • 3.1. Functions and Exceptions
        • 3.2. Format Strings
          • 3.2.1. Byte Order, Size, and Alignment
          • 3.2.2. Format Characters
          • 3.2.3. Examples
        • 3.3. Classes
      • 4. difflib — Helpers for computing deltas
        • 4.1. SequenceMatcher Objects
        • 4.2. SequenceMatcher Examples
        • 4.3. Differ Objects
        • 4.4. Differ Example
        • 4.5. A command-line interface to difflib
      • 5. StringIO — Read and write strings as files
      • 6. cStringIO — Faster version of StringIO
      • 7. textwrap — Text wrapping and filling
      • 8. codecs — Codec registry and base classes
        • 8.1. Codec Base Classes
          • 8.1.1. Codec Objects
          • 8.1.2. IncrementalEncoder Objects
          • 8.1.3. IncrementalDecoder Objects
          • 8.1.4. StreamWriter Objects
          • 8.1.5. StreamReader Objects
          • 8.1.6. StreamReaderWriter Objects
          • 8.1.7. StreamRecoder Objects
        • 8.2. Encodings and Unicode
        • 8.3. Standard Encodings
        • 8.4. Python Specific Encodings
        • 8.5. encodings.idna — Internationalized Domain Names in Applications
        • 8.6. encodings.utf_8_sig — UTF-8 codec with BOM signature
      • 9. unicodedata — Unicode Database
      • 10. stringprep — Internet String Preparation
      • 11. (deprecated) fpformat — Floating point conversions
    • 08. Data Types
      • 1. datetime — Basic date and time types
        • 1.1. Available Types
        • 1.2. timedelta Objects
        • 1.3. date Objects
        • 1.4. datetime Objects
        • 1.5. time Objects
        • 1.6. tzinfo Objects
        • 1.7. strftime() and strptime() Behavior
      • 2. calendar — General calendar-related functions
      • 3. collections — High-performance container datatypes
        • 3.1. Counter objects
        • 3.2. deque objects
          • 3.2.1. deque Recipes
        • 3.3. defaultdict objects
          • 3.3.1. defaultdict Examples
        • 3.4. namedtuple() Factory Function for Tuples with Named Fields
        • 3.5. OrderedDict objects
          • 3.5.1. OrderedDict Examples and Recipes
        • 3.6. Collections Abstract Base Classes
      • 4. heapq — Heap queue algorithm
        • 4.1. Basic Examples
        • 4.2. Priority Queue Implementation Notes
        • 4.3. Theory
      • 5. bisect — Array bisection algorithm
        • 5.1. Searching Sorted Lists
        • 5.2. Other Examples
      • 6. array — Efficient arrays of numeric values
      • 7. sets — Unordered collections of unique elements
        • 7.1. Set Objects
        • 7.2. Example
        • 7.3. Protocol for automatic conversion to immutable
        • 7.4. Comparison to the built-in set types
      • 8. sched — Event scheduler
        • 8.1. Scheduler Objects
      • 9. mutex — Mutual exclusion support
        • 9.1. Mutex Objects
      • 10. Queue — A synchronized queue class
        • 10.1. Queue Objects
      • 11. weakref — Weak references
        • 11.1. Weak Reference Objects
        • 11.2. Example
      • 12. UserDict — Class wrapper for dictionary objects
      • 13. UserList — Class wrapper for list objects
      • 14. UserString — Class wrapper for string objects
      • 15. types — Names for built-in types
      • 16. new — Creation of runtime internal objects
      • 17. copy — Shallow and deep copy operations
      • 18. pprint — Data pretty printer
        • 18.1. PrettyPrinter Objects
        • 18.2. pprint Example
      • 19. repr — Alternate repr() implementation
        • 19.1. Repr Objects
        • 19.2. Subclassing Repr Objects
    • 09 Numeric and Mathematical Modules
      • 1. numbers — Numeric abstract base classes
        • 1.1. The numeric tower
        • 1.2. Notes for type implementors
          • 1.2.1. Adding More Numeric ABCs
          • 1.2.2. Implementing the arithmetic operations
      • 2. math — Mathematical functions
        • 2.1. Number-theoretic and representation functions
        • 2.2. Power and logarithmic functions
        • 2.3. Trigonometric functions
        • 2.4. Angular conversion
        • 2.5. Hyperbolic functions
        • 2.6. Special functions
        • 2.7. Constants
      • 3. cmath — Mathematical functions for complex numbers
        • 3.1. Conversions to and from polar coordinates
        • 3.2. Power and logarithmic functions
        • 3.3. Trigonometric functions
        • 3.4. Hyperbolic functions
        • 3.5. Classification functions
        • 3.6. Constants
      • 4. decimal — Decimal fixed point and floating point arithmetic
        • 4.1. Quick-start Tutorial
        • 4.2. Decimal objects
          • 4.2.1. Logical operands
        • 4.3. Context objects
        • 4.4. Signals
        • 4.5. Floating Point Notes
          • 4.5.1. Mitigating round-off error with increased precision
          • 4.5.2. Special values
        • 4.6. Working with threads
        • 4.7. Recipes
        • 4.8. Decimal FAQ
      • 5. fractions — Rational numbers
      • 6. random — Generate pseudo-random numbers
      • 7. itertools — Functions creating iterators for efficient looping
        • 7.1. Itertool functions
        • 7.2. Recipes
      • 8. functools — Higher-order functions and operations on callable objects
        • 8.1. partial Objects
      • 9. operator — Standard operators as functions
        • 9.1. Mapping Operators to Functions
    • 10 File and Directory Access
      • 1. os.path — Common pathname manipulations
      • 2. fileinput — Iterate over lines from multiple input streams
      • 3. stat — Interpreting stat() results
      • 4. statvfs — Constants used with os.statvfs()
      • 5. filecmp — File and Directory Comparisons
        • 5.1. The dircmp class
      • 6. tempfile — Generate temporary files and directories
      • 7. glob — Unix style pathname pattern expansion
      • 8. fnmatch — Unix filename pattern matching
      • 9. linecache — Random access to text lines
      • 10. shutil — High-level file operations
        • 10.1. Directory and files operations
          • 10.1.1. copytree example
        • 10.2. Archiving operations
          • 10.2.1. Archiving example
      • 11. dircache — Cached directory listings
      • 12. macpath — Mac OS 9 path manipulation functions
  • Ch 11 - 15
    • 11. Data Persistence
      • 1. pickle — Python object serialization
        • 1.1. Relationship to other Python modules
        • 1.2. Data stream format
        • 1.3. Usage
        • 1.4. What can be pickled and unpickled?
        • 1.5. The pickle protocol
          • 1.5.1. Pickling and unpickling normal class instances
          • 1.5.2. Pickling and unpickling extension types
          • 1.5.3. Pickling and unpickling external objects
        • 1.6. Subclassing Unpicklers
        • 1.7. Example
      • 2. cPickle — A faster pickle
      • 3. copy_reg — Register pickle support functions
        • 3.1. Example
      • 4. shelve — Python object persistence
        • 4.1. Restrictions
        • 4.2. Example
      • 5. marshal — Internal Python object serialization
      • 6. anydbm — Generic access to DBM-style databases
      • 7. whichdb — Guess which DBM module created a database
      • 8. dbm — Simple “database” interface
      • 9. gdbm — GNU’s reinterpretation of dbm
      • 10. (deprecated) dbhash — DBM-style interface to the BSD database library
        • 10.1. Database Objects
      • 11. (deprecated) bsddb — Interface to Berkeley DB library
        • 11.1. Hash, BTree and Record Objects
      • 12. dumbdbm — Portable DBM implementation
        • 12.1. Dumbdbm Objects
      • 13. sqlite3 — DB-API 2.0 interface for SQLite databases
        • 13.1. Module functions and constants
        • 13.2. Connection Objects
        • 13.3. Cursor Objects
        • 13.4. Row Objects
        • 13.5. SQLite and Python types
          • 13.5.1. Introduction
          • 13.5.2. Using adapters to store additional Python types in SQLite databases
            • 13.5.2.1. Letting your object adapt itself
            • 13.5.2.2. Registering an adapter callable
          • 13.5.3. Converting SQLite values to custom Python types
          • 13.5.4. Default adapters and converters
        • 13.6. Controlling Transactions
        • 13.7. Using sqlite3 efficiently
          • 13.7.1. Using shortcut methods
          • 13.7.2. Accessing columns by name instead of by index
          • 13.7.3. Using the connection as a context manager
        • 13.8. Common issues
          • 13.8.1. Multithreading
    • 12 Data Compression and Archiving
      • 1. zlib — Compression compatible with gzip
      • 2. gzip — Support for gzip files
        • 2.1. Examples of usage
      • 3. bz2 — Compression compatible with bzip2
        • 3.1. (De)compression of files
        • 3.2. Sequential (de)compression
        • 3.3. One-shot (de)compression
      • 4. zipfile — Work with ZIP archives
        • 4.1. ZipFile Objects
        • 4.2. PyZipFile Objects
        • 4.3. ZipInfo Objects
      • 5. tarfile — Read and write tar archive files
        • 5.1. TarFile Objects
        • 5.2. TarInfo Objects
        • 5.3. Examples
        • 5.4. Supported tar formats
        • 5.5. Unicode issues
    • 13 File Formats
      • csv — CSV File Reading and Writing
        • Module Contents
        • Dialects and Formatting Parameters
        • Reader Objects
        • Writer Objects
        • Examples
      • ConfigParser — Configuration file parser
        • RawConfigParser Objects
        • ConfigParser Objects
        • SafeConfigParser Objects
        • Examples
      • robotparser — Parser for robots.txt
      • netrc — netrc file processing
        • netrc Objects
      • xdrlib — Encode and decode XDR data
        • Packer Objects
        • Unpacker Objects
        • Exceptions
      • plistlib — Generate and parse Mac OS X .plist files
        • Examples
    • 14 Cryptographic Services
      • 1. hashlib — Secure hashes and message digests
        • 1.1. Key derivation
      • 2. hmac — Keyed-Hashing for Message Authentication
      • 3. md5 — MD5 message digest algorithm
      • 4. sha — SHA-1 message digest algorithm
    • 15 Generic Operating System Services
      • 1. os — Miscellaneous operating system interfaces
        • 1.1. Process Parameters
        • 1.2. File Object Creation
        • 1.3. File Descriptor Operations
          • 1.3.1. open() flag constants
        • 1.4. Files and Directories
        • 1.5. Process Management
        • 1.6. Miscellaneous System Information
        • 1.7. Miscellaneous Functions
      • 2. io — Core tools for working with streams
        • 2.1. Module Interface
        • 2.2. I/O Base Classes
        • 2.3. Raw File I/O
        • 2.4. Buffered Streams
        • 2.5. Text I/O
        • 2.6. Advanced topics
          • 2.6.1. Performance
            • 2.6.1.1. Binary I/O
            • 2.6.1.2. Text I/O
          • 2.6.2. Multi-threading
          • 2.6.3. Reentrancy
      • 3. argparse — Parser for command-line options, arguments and sub-commands
        • 3.1. Example
          • 3.1.1. Creating a parser
          • 3.1.2. Adding arguments
          • 3.1.3. Parsing arguments
        • 3.2. ArgumentParser objects
          • 3.2.1. prog
          • 3.2.2. usage
          • 3.2.3. description
          • 3.2.4. epilog
          • 3.2.5. parents
          • 3.2.6. formatter_class
          • 3.2.7. prefix_chars
          • 3.2.8. fromfile_prefix_chars
          • 3.2.9. argument_default
          • 3.2.10. conflict_handler
          • 3.2.11. add_help
        • 3.3. The add_argument() method
          • 3.3.1. name or flags
          • 3.3.2. action
          • 3.3.3. nargs
          • 3.3.4. const
          • 3.3.5. default
          • 3.3.6. type
          • 3.3.7. choices
          • 3.3.8. required
          • 3.3.9. help
          • 3.3.10. metavar
          • 3.3.11. dest
          • 3.3.12. Action classes
        • 3.4. The parse_args() method
          • 3.4.1. Option value syntax
          • 3.4.2. Invalid arguments
          • 3.4.3. Arguments containing -
          • 3.4.4. Argument abbreviations (prefix matching)
          • 3.4.5. Beyond sys.argv
          • 3.4.6. The Namespace object
        • 3.5. Other utilities
          • 3.5.1. Sub-commands
          • 3.5.2. FileType objects
          • 3.5.3. Argument groups
          • 3.5.4. Mutual exclusion
          • 3.5.5. Parser defaults
          • 3.5.6. Printing help
          • 3.5.7. Partial parsing
          • 3.5.8. Customizing file parsing
          • 3.5.9. Exiting methods
        • 3.6. Upgrading optparse code
      • 4. optparse — Parser for command line options
        • 4.1. Background
          • 4.1.1. Terminology
          • 4.1.2. What are options for?
          • 4.1.3. What are positional arguments for?
        • 4.2. Tutorial
          • 4.2.1. Understanding option actions
          • 4.2.2. The store action
          • 4.2.3. Handling boolean (flag) options
          • 4.2.4. Other actions
          • 4.2.5. Default values
          • 4.2.6. Generating help
            • 4.2.6.1. Grouping Options
          • 4.2.7. Printing a version string
          • 4.2.8. How optparse handles errors
          • 4.2.9. Putting it all together
        • 4.3. Reference Guide
          • 4.3.1. Creating the parser
          • 4.3.2. Populating the parser
          • 4.3.3. Defining options
          • 4.3.4. Option attributes
          • 4.3.5. Standard option actions
          • 4.3.6. Standard option types
          • 4.3.7. Parsing arguments
          • 4.3.8. Querying and manipulating your option parser
          • 4.3.9. Conflicts between options
          • 4.3.10. Cleanup
          • 4.3.11. Other methods
        • 4.4. Option Callbacks
          • 4.4.1. Defining a callback option
          • 4.4.2. How callbacks are called
          • 4.4.3. Raising errors in a callback
          • 4.4.4. Callback example 1: trivial callback
          • 4.4.5. Callback example 2: check option order
          • 4.4.6. Callback example 3: check option order (generalized)
          • 4.4.7. Callback example 4: check arbitrary condition
          • 4.4.8. Callback example 5: fixed arguments
          • 4.4.9. Callback example 6: variable arguments
        • 4.5. Extending optparse
          • 4.5.1. Adding new types
          • 4.5.2. Adding new actions
      • 5. getopt — C-style parser for command line options
      • 6. logging — Logging facility for Python
        • 6.1. Logger Objects
        • 6.2. Logging Levels
        • 6.3. Handler Objects
        • 6.4. Formatter Objects
        • 6.5. Filter Objects
        • 6.6. LogRecord Objects
        • 6.7. LogRecord attributes
        • 6.8. LoggerAdapter Objects
        • 6.9. Thread Safety
        • 6.10. Module-Level Functions
        • 6.11. Integration with the warnings module
      • 7. logging.config — Logging configuration
        • 7.1. Configuration functions
        • 7.2. Configuration dictionary schema
          • 7.2.1. Dictionary Schema Details
          • 7.2.2. Incremental Configuration
          • 7.2.3. Object connections
          • 7.2.4. User-defined objects
          • 7.2.5. Access to external objects
          • 7.2.6. Access to internal objects
          • 7.2.7. Import resolution and custom importers
        • 7.3. Configuration file format
      • 8. logging.handlers — Logging handlers
        • 8.1. StreamHandler
        • 8.2. FileHandler
        • 8.3. NullHandler
        • 8.4. WatchedFileHandler
        • 8.5. RotatingFileHandler
        • 8.6. TimedRotatingFileHandler
        • 8.7. SocketHandler
        • 8.8. DatagramHandler
        • 8.9. SysLogHandler
        • 8.10. NTEventLogHandler
        • 8.11. SMTPHandler
        • 8.12. MemoryHandler
        • 8.13. HTTPHandler
      • 9. getpass — Portable password input
      • 10. curses — Terminal handling for character-cell displays
        • 10.1. Functions
        • 10.2. Window Objects
        • 10.3. Constants
      • 11. curses.textpad — Text input widget for curses programs
        • 11.1. Textbox objects
      • 12. curses.ascii — Utilities for ASCII characters
      • 13. curses.panel — A panel stack extension for curses
        • 13.1. Functions
        • 13.2. Panel Objects
      • 14. platform — Access to underlying platform’s identifying data
        • 14.1. Cross Platform
        • 14.2. Java Platform
        • 14.3. Windows Platform
          • 14.3.1. Win95/98 specific
        • 14.4. Mac OS Platform
        • 14.5. Unix Platforms
      • 15. errno — Standard errno system symbols
      • 16. ctypes — A foreign function library for Python
        • 16.1. ctypes tutorial
          • 16.1.1. Loading dynamic link libraries
          • 16.1.2. Accessing functions from loaded dlls
          • 16.1.3. Calling functions
          • 16.1.4. Fundamental data types
          • 16.1.5. Calling functions, continued
          • 16.1.6. Calling functions with your own custom data types
          • 16.1.7. Specifying the required argument types (function prototypes)
          • 16.1.8. Return types
          • 16.1.9. Passing pointers (or: passing parameters by reference)
          • 16.1.10. Structures and unions
          • 16.1.11. Structure/union alignment and byte order
          • 16.1.12. Bit fields in structures and unions
          • 16.1.13. Arrays
          • 16.1.14. Pointers
          • 16.1.15. Type conversions
          • 16.1.16. Incomplete Types
          • 16.1.17. Callback functions
          • 16.1.18. Accessing values exported from dlls
          • 16.1.19. Surprises
          • 16.1.20. Variable-sized data types
        • 16.2. ctypes reference
          • 16.2.1. Finding shared libraries
          • 16.2.2. Loading shared libraries
          • 16.2.3. Foreign functions
          • 16.2.4. Function prototypes
          • 16.2.5. Utility functions
          • 16.2.6. Data types
          • 16.2.7. Fundamental data types
          • 16.2.8. Structured data types
          • 16.2.9. Arrays and pointers
  • Ch 16 - 20
    • 16 Optional Operating System Services
      • 1. select — Waiting for I/O completion
        • 1.1. Edge and Level Trigger Polling (epoll) Objects
        • 1.2. Polling Objects
        • 1.3. Kqueue Objects
        • 1.4. Kevent Objects
      • 2. threading — Higher-level threading interface
        • 2.1. Thread Objects
        • 2.2. Lock Objects
        • 2.3. RLock Objects
        • 2.4. Condition Objects
        • 2.5. Semaphore Objects
          • 2.5.1. Semaphore Example
        • 2.6. Event Objects
        • 2.7. Timer Objects
        • 2.8. Using locks, conditions, and semaphores in the with statement
        • 2.9. Importing in threaded code
      • 3. thread — Multiple threads of control
      • 4. dummy_threading — Drop-in replacement for the threading module
      • 5. dummy_thread — Drop-in replacement for the thread module
      • 6. multiprocessing — Process-based “threading” interface
        • 6.1. Introduction
          • 6.1.1. The Process class
          • 6.1.2. Exchanging objects between processes
          • 6.1.3. Synchronization between processes
          • 6.1.4. Sharing state between processes
          • 6.1.5. Using a pool of workers
        • 6.2. Reference
          • 6.2.1. Process and exceptions
          • 6.2.2. Pipes and Queues
          • 6.2.3. Miscellaneous
          • 6.2.4. Connection Objects
          • 6.2.5. Synchronization primitives
          • 6.2.6. Shared ctypes Objects
            • 6.2.6.1. The multiprocessing.sharedctypes module
          • 6.2.7. Managers
            • 6.2.7.1. Customized managers
            • 6.2.7.2. Using a remote manager
          • 6.2.8. Proxy Objects
            • 6.2.8.1. Cleanup
          • 6.2.9. Process Pools
          • 6.2.10. Listeners and Clients
            • 6.2.10.1. Address Formats
          • 6.2.11. Authentication keys
          • 6.2.12. Logging
          • 6.2.13. The multiprocessing.dummy module
        • 6.3. Programming guidelines
          • 6.3.1. All platforms
          • 6.3.2. Windows
        • 6.4. Examples
      • 7. mmap — Memory-mapped file support
      • 8. readline — GNU readline interface
        • 8.1. Init file
        • 8.2. Line buffer
        • 8.3. History file
        • 8.4. History list
        • 8.5. Startup hooks
        • 8.6. Completion
        • 8.7. Example
      • 9. rlcompleter — Completion function for GNU readline
        • 9.1. Completer Objects
    • 17 Interprocess Communication and Networking
      • 1. subprocess — Subprocess management
        • 1.1. Using the subprocess Module
          • 1.1.1. Frequently Used Arguments
          • 1.1.2. Popen Constructor
          • 1.1.3. Exceptions
          • 1.1.4. Security
        • 1.2. Popen Objects
        • 1.3. Windows Popen Helpers
          • 1.3.1. Constants
        • 1.4. Replacing Older Functions with the subprocess Module
          • 1.4.1. Replacing /bin/sh shell backquote
          • 1.4.2. Replacing shell pipeline
          • 1.4.3. Replacing os.system()
          • 1.4.4. Replacing the os.spawn family
          • 1.4.5. Replacing os.popen(), os.popen2(), os.popen3()
          • 1.4.6. Replacing functions from the popen2 module
        • 1.5. Notes
          • 1.5.1. Converting an argument sequence to a string on Windows
      • 2. socket — Low-level networking interface
        • 2.1. Socket Objects
        • 2.2. Example
      • 3. ssl — TLS/SSL wrapper for socket objects
        • 3.1. Functions, Constants, and Exceptions
          • 3.1.1. Socket creation
          • 3.1.2. Context creation
          • 3.1.3. Random generation
          • 3.1.4. Certificate handling
          • 3.1.5. Constants
        • 3.2. SSL Sockets
        • 3.3. SSL Contexts
        • 3.4. Certificates
          • 3.4.1. Certificate chains
          • 3.4.2. CA certificates
          • 3.4.3. Combined key and certificate
          • 3.4.4. Self-signed certificates
        • 3.5. Examples
          • 3.5.1. Testing for SSL support
          • 3.5.2. Client-side operation
          • 3.5.3. Server-side operation
        • 3.6. Notes on non-blocking sockets
        • 3.7. Security considerations
          • 3.7.1. Best defaults
          • 3.7.2. Manual settings
            • 3.7.2.1. Verifying certificates
            • 3.7.2.2. Protocol versions
            • 3.7.2.3. Cipher selection
          • 3.7.3. Multi-processing
      • 4. signal — Set handlers for asynchronous events
        • 4.1. Example
      • 5. popen2 — Subprocesses with accessible I/O streams
        • 5.1. Popen3 and Popen4 Objects
        • 5.2. Flow Control Issues
      • 6. asyncore — Asynchronous socket handler
        • 6.1. asyncore Example basic HTTP client
        • 6.2. asyncore Example basic echo server
      • 7. asynchat — Asynchronous socket command/response handler
        • 7.1. asynchat - Auxiliary Classes
        • 7.2. asynchat Example
    • 18 Internet Data Handling
      • 1. email — An email and MIME handling package
        • 1.1. Package History
        • 1.2. Differences from mimelib
      • 2. json — JSON encoder and decoder
        • 2.1. Basic Usage
        • 2.2. Encoders and Decoders
        • 2.3. Standard Compliance and Interoperability
          • 2.3.1. Character Encodings
          • 2.3.2. Infinite and NaN Number Values
          • 2.3.3. Repeated Names Within an Object
          • 2.3.4. Top-level Non-Object, Non-Array Values
          • 2.3.5. Implementation Limitations
      • 3. mailcap — Mailcap file handling
      • 4. mailbox — Manipulate mailboxes in various formats
        • 4.1. Mailbox objects
          • 4.1.1. Maildir
          • 4.1.2. mbox
          • 4.1.3. MH
          • 4.1.4. Babyl
          • 4.1.5. MMDF
        • 4.2. Message objects
          • 4.2.1. MaildirMessage
          • 4.2.2. mboxMessage
          • 4.2.3. MHMessage
          • 4.2.4. BabylMessage
          • 4.2.5. MMDFMessage
        • 4.3. Exceptions
        • 4.4. Deprecated classes and methods
        • 4.5. Examples
      • 5. (depr) mhlib — Access to MH mailboxes
        • 5.1. MH Objects
        • 5.2. Folder Objects
        • 5.3. Message Objects
      • 6. (depr) mimetools — Tools for parsing MIME messages
        • 6.1. Additional Methods of Message Objects
      • 7. mimetypes — Map filenames to MIME types
        • 7.1. MimeTypes Objects
      • 8. (depr) MimeWriter — Generic MIME file writer
        • 8.1. MimeWriter Objects
      • 9. (depr) mimify — MIME processing of mail messages
      • 10. (depr) multifile — Support for files containing distinct parts
        • 10.1. MultiFile Objects
        • 10.2. MultiFile Example
      • 11. (depr) rfc822 — Parse RFC 2822 mail headers
        • 11.1. Message Objects
        • 11.2. AddressList Objects
      • 12. base64 — RFC 3548: Base16, Base32, Base64 Data Encodings
      • 13. binhex — Encode and decode binhex4 files
        • 13.1. Notes
      • 14. binascii — Convert between binary and ASCII
      • 15. quopri — Encode and decode MIME quoted-printable data
      • 16. uu — Encode and decode uuencode files
    • 19 Structured Markup Processing Tools
      • 1. HTMLParser — Simple HTML and XHTML parser
        • 1.1. Example HTML Parser Application
        • 1.2. HTMLParser Methods
        • 1.3. Examples
      • 2. (depr) sgmllib — Simple SGML parser
      • 3. (depr) htmllib — A parser for HTML documents
        • 3.1. HTMLParser Objects
      • 4. htmlentitydefs — Definitions of HTML general entities
      • 5. XML Processing Modules
      • 6. XML vulnerabilities
        • 6.1. defused packages
      • 7. xml.etree.ElementTree — The ElementTree XML API
        • 7.1. Tutorial
          • 7.1.1. XML tree and elements
          • 7.1.2. Parsing XML
          • 7.1.3. Finding interesting elements
          • 7.1.4. Modifying an XML File
          • 7.1.5. Building XML documents
          • 7.1.6. Parsing XML with Namespaces
          • 7.1.7. Additional resources
        • 7.2. XPath support
          • 7.2.1. Example
          • 7.2.2. Supported XPath syntax
        • 7.3. Reference
          • 7.3.1. Functions
          • 7.3.2. Element Objects
          • 7.3.3. ElementTree Objects
          • 7.3.4. QName Objects
          • 7.3.5. TreeBuilder Objects
          • 7.3.6. XMLParser Objects
      • 8. xml.dom — The Document Object Model API
        • 8.1. Module Contents
        • 8.2. Objects in the DOM
          • 8.2.1. DOMImplementation Objects
          • 8.2.2. Node Objects
          • 8.2.3. NodeList Objects
          • 8.2.4. DocumentType Objects
          • 8.2.5. Document Objects
          • 8.2.6. Element Objects
          • 8.2.7. Attr Objects
          • 8.2.8. NamedNodeMap Objects
          • 8.2.9. Comment Objects
          • 8.2.10. Text and CDATASection Objects
          • 8.2.11. ProcessingInstruction Objects
          • 8.2.12. Exceptions
        • 8.3. Conformance
          • 8.3.1. Type Mapping
          • 8.3.2. Accessor Methods
      • 9. xml.dom.minidom — Minimal DOM implementation
        • 9.1. DOM Objects
        • 9.2. DOM Example
        • 9.3. minidom and the DOM standard
      • 10. xml.dom.pulldom — Support for building partial DOM trees
        • 10.1. DOMEventStream Objects
      • 11. xml.sax — Support for SAX2 parsers
        • 11.1. SAXException Objects
      • 12. xml.sax.handler — Base classes for SAX handlers
        • 12.1. ContentHandler Objects
        • 12.2. DTDHandler Objects
        • 12.3. EntityResolver Objects
        • 12.4. ErrorHandler Objects
      • 13. xml.sax.saxutils — SAX Utilities
      • 14. xml.sax.xmlreader — Interface for XML parsers
        • 14.1. XMLReader Objects
        • 14.2. IncrementalParser Objects
        • 14.3. Locator Objects
        • 14.4. InputSource Objects
        • 14.5. The Attributes Interface
        • 14.6. The AttributesNS Interface
      • 15. xml.parsers.expat — Fast XML parsing using Expat
        • 15.1. XMLParser Objects
        • 15.2. ExpatError Exceptions
        • 15.3. Example
        • 15.4. Content Model Descriptions
        • 15.5. Expat error constants
    • 20a Internet Protocols and Support
      • 1. webbrowser — Convenient Web-browser controller
        • 1.1. Browser Controller Objects
      • 2. cgi — Common Gateway Interface support
        • 2.1. Introduction
        • 2.2. Using the cgi module
        • 2.3. Higher Level Interface
        • 2.4. Old classes
        • 2.5. Functions
        • 2.6. Caring about security
        • 2.7. Installing your CGI script on a Unix system
        • 2.8. Testing your CGI script
        • 2.9. Debugging CGI scripts
        • 2.10. Common problems and solutions
      • 3. cgitb — Traceback manager for CGI scripts
      • 4. wsgiref — WSGI Utilities and Reference Implementation
        • 4.1. wsgiref.util – WSGI environment utilities
        • 4.2. wsgiref.headers – WSGI response header tools
        • 4.3. wsgiref.simple_server – a simple WSGI HTTP server
        • 4.4. wsgiref.validate — WSGI conformance checker
        • 4.5. wsgiref.handlers – server/gateway base classes
        • 4.6. Examples
      • 5. urllib — Open arbitrary resources by URL
        • 5.1. High-level interface
        • 5.2. Utility functions
        • 5.3. URL Opener objects
        • 5.4. urllib Restrictions
        • 5.5. Examples
      • 6. urllib2 — extensible library for opening URLs
        • 6.1. Request Objects
        • 6.2. OpenerDirector Objects
        • 6.3. BaseHandler Objects
        • 6.4. HTTPRedirectHandler Objects
        • 6.5. HTTPCookieProcessor Objects
        • 6.6. ProxyHandler Objects
        • 6.7. HTTPPasswordMgr Objects
        • 6.8. AbstractBasicAuthHandler Objects
        • 6.9. HTTPBasicAuthHandler Objects
        • 6.10. ProxyBasicAuthHandler Objects
        • 6.11. AbstractDigestAuthHandler Objects
        • 6.12. HTTPDigestAuthHandler Objects
        • 6.13. ProxyDigestAuthHandler Objects
        • 6.14. HTTPHandler Objects
        • 6.15. HTTPSHandler Objects
        • 6.16. FileHandler Objects
        • 6.17. FTPHandler Objects
        • 6.18. CacheFTPHandler Objects
        • 6.19. UnknownHandler Objects
        • 6.20. HTTPErrorProcessor Objects
        • 6.21. Examples
      • 7. httplib — HTTP protocol client
        • 7.1. HTTPConnection Objects
        • 7.2. HTTPResponse Objects
        • 7.3. Examples
      • 8. ftplib — FTP protocol client
        • 8.1. FTP Objects
        • 8.2. FTP_TLS Objects
      • 9. poplib — POP3 protocol client
        • 9.1. POP3 Objects
        • 9.2. POP3 Example
      • 10. imaplib — IMAP4 protocol client
        • 10.1. IMAP4 Objects
        • 10.2. IMAP4 Example
      • 11. nntplib — NNTP protocol client
        • 11.1. NNTP Objects
      • 12. smtplib — SMTP protocol client
        • 12.1. SMTP Objects
        • 12.2. SMTP Example
      • 13. smtpd — SMTP Server
        • 13.1. SMTPServer Objects
        • 13.2. DebuggingServer Objects
        • 13.3. PureProxy Objects
        • 13.4. MailmanProxy Objects
    • 20b Internet Protocols and Support
      • 1. telnetlib — Telnet client
        • 1.1. Telnet Objects
        • 1.2. Telnet Example
      • 2. uuid — UUID objects according to RFC 4122
        • 2.1. Example
      • 3. urlparse — Parse URLs into components
        • 3.1. Results of urlparse() and urlsplit()
      • 4. SocketServer — A framework for network servers
        • 4.1. Server Creation Notes
        • 4.2. Server Objects
        • 4.3. Request Handler Objects
        • 4.4. Examples
          • 4.4.1. SocketServer.TCPServer Example
          • 4.4.2. SocketServer.UDPServer Example
          • 4.4.3. Asynchronous Mixins
      • 5. BaseHTTPServer — Basic HTTP server
        • 5.1. More examples
      • 6. SimpleHTTPServer — Simple HTTP request handler
      • 7. CGIHTTPServer — CGI-capable HTTP request handler
      • 8. cookielib — Cookie handling for HTTP clients
        • 8.1. CookieJar and FileCookieJar Objects
        • 8.2. FileCookieJar subclasses and co-operation with web browsers
        • 8.3. CookiePolicy Objects
        • 8.4. DefaultCookiePolicy Objects
        • 8.5. Cookie Objects
        • 8.6. Examples
      • 9. Cookie — HTTP state management
        • 9.1. Cookie Objects
        • 9.2. Morsel Objects
        • 9.3. Example
      • 10. xmlrpclib — XML-RPC client access
        • 10.1. ServerProxy Objects
        • 10.2. Boolean Objects
        • 10.3. DateTime Objects
        • 10.4. Binary Objects
        • 10.5. Fault Objects
        • 10.6. ProtocolError Objects
        • 10.7. MultiCall Objects
        • 10.8. Convenience Functions
        • 10.9. Example of Client Usage
        • 10.10. Example of Client and Server Usage
      • 11. SimpleXMLRPCServer — Basic XML-RPC server
        • 11.1. SimpleXMLRPCServer Objects
          • 11.1.1. SimpleXMLRPCServer Example
        • 11.2. CGIXMLRPCRequestHandler
      • 12. DocXMLRPCServer — Self-documenting XML-RPC server
        • 12.1. DocXMLRPCServer Objects
        • 12.2. DocCGIXMLRPCRequestHandler
  • Ch 21 - 25
    • 21 Multimedia Services
      • 1. audioop — Manipulate raw audio data
      • 2. imageop — Manipulate raw image data
      • 3. aifc — Read and write AIFF and AIFC files
      • 4. sunau — Read and write Sun AU files
        • 4.1. AU_read Objects
        • 4.2. AU_write Objects
      • 5. wave — Read and write WAV files
        • 5.1. Wave_read Objects
        • 5.2. Wave_write Objects
      • 6. chunk — Read IFF chunked data
      • 7. colorsys — Conversions between color systems
      • 8. imghdr — Determine the type of an image
      • 9. sndhdr — Determine type of sound file
      • 10. ossaudiodev — Access to OSS-compatible audio devices
        • 10.1. Audio Device Objects
        • 10.2. Mixer Device Objects
    • 22 Internationalization
      • 1. gettext — Multilingual internationalization services
        • 1.1. GNU gettext API
        • 1.2. Class-based API
          • 1.2.1. The NullTranslations class
          • 1.2.2. The GNUTranslations class
          • 1.2.3. Solaris message catalog support
          • 1.2.4. The Catalog constructor
        • 1.3. Internationalizing your programs and modules
          • 1.3.1. Localizing your module
          • 1.3.2. Localizing your application
          • 1.3.3. Changing languages on the fly
          • 1.3.4. Deferred translations
          • 1.3.5. gettext() vs. lgettext()
        • 1.4. Acknowledgements
      • 2. locale — Internationalization services
        • 2.1. Background, details, hints, tips and caveats
        • 2.2. For extension writers and programs that embed Python
        • 2.3. Access to message catalogs
    • 23 Program Frameworks
      • 1. cmd — Support for line-oriented command interpreters
        • 1.1. Cmd Objects
      • 2. shlex — Simple lexical analysis
        • 2.1. shlex Objects
        • 2.2. Parsing Rules
    • 24 Graphical User Interfaces with Tk
      • 1. Tkinter — Python interface to Tcl/Tk
        • 1.1. Tkinter Modules
        • 1.2. Tkinter Life Preserver
          • 1.2.1. How To Use This Section
          • 1.2.2. A Simple Hello World Program
        • 1.3. A (Very) Quick Look at Tcl/Tk
        • 1.4. Mapping Basic Tk into Tkinter
        • 1.5. How Tk and Tkinter are Related
        • 1.6. Handy Reference
          • 1.6.1. Setting Options
          • 1.6.2. The Packer
          • 1.6.3. Packer Options
          • 1.6.4. Coupling Widget Variables
          • 1.6.5. The Window Manager
          • 1.6.6. Tk Option Data Types
          • 1.6.7. Bindings and Events
          • 1.6.8. The index Parameter
          • 1.6.9. Images
        • 1.7. File Handlers
      • 2. ttk — Tk themed widgets
        • 2.1. Using Ttk
        • 2.2. Ttk Widgets
        • 2.3. Widget
          • 2.3.1. Standard Options
          • 2.3.2. Scrollable Widget Options
          • 2.3.3. Label Options
          • 2.3.4. Compatibility Options
          • 2.3.5. Widget States
          • 2.3.6. ttk.Widget
        • 2.4. Combobox
          • 2.4.1. Options
          • 2.4.2. Virtual events
          • 2.4.3. ttk.Combobox
        • 2.5. Notebook
          • 2.5.1. Options
          • 2.5.2. Tab Options
          • 2.5.3. Tab Identifiers
          • 2.5.4. Virtual Events
          • 2.5.5. ttk.Notebook
        • 2.6. Progressbar
          • 2.6.1. Options
          • 2.6.2. ttk.Progressbar
        • 2.7. Separator
          • 2.7.1. Options
        • 2.8. Sizegrip
          • 2.8.1. Platform-specific notes
          • 2.8.2. Bugs
        • 2.9. Treeview
          • 2.9.1. Options
          • 2.9.2. Item Options
          • 2.9.3. Tag Options
          • 2.9.4. Column Identifiers
          • 2.9.5. Virtual Events
          • 2.9.6. ttk.Treeview
        • 2.10. Ttk Styling
          • 2.10.1. Layouts
      • 3. Tix — Extension widgets for Tk
        • 3.1. Using Tix
        • 3.2. Tix Widgets
          • 3.2.1. Basic Widgets
          • 3.2.2. File Selectors
          • 3.2.3. Hierarchical ListBox
          • 3.2.4. Tabular ListBox
          • 3.2.5. Manager Widgets
          • 3.2.6. Image Types
          • 3.2.7. Miscellaneous Widgets
          • 3.2.8. Form Geometry Manager
        • 3.3. Tix Commands
      • 4. ScrolledText — Scrolled Text Widget
      • 5. turtle — Turtle graphics for Tk
        • 5.1. Introduction
        • 5.2. Overview over available Turtle and Screen methods
          • 5.2.1. Turtle methods
          • 5.2.2. Methods of TurtleScreen/Screen
        • 5.3. Methods of RawTurtle/Turtle and corresponding functions
          • 5.3.1. Turtle motion
          • 5.3.2. Tell Turtle’s state
          • 5.3.3. Settings for measurement
          • 5.3.4. Pen control
            • 5.3.4.1. Drawing state
            • 5.3.4.2. Color control
            • 5.3.4.3. Filling
            • 5.3.4.4. More drawing control
          • 5.3.5. Turtle state
            • 5.3.5.1. Visibility
            • 5.3.5.2. Appearance
          • 5.3.6. Using events
          • 5.3.7. Special Turtle methods
          • 5.3.8. Excursus about the use of compound shapes
        • 5.4. Methods of TurtleScreen/Screen and corresponding functions
          • 5.4.1. Window control
          • 5.4.2. Animation control
          • 5.4.3. Using screen events
          • 5.4.4. Settings and special methods
          • 5.4.5. Methods specific to Screen, not inherited from TurtleScreen
        • 5.5. The public classes of the module turtle
        • 5.6. Help and configuration
          • 5.6.1. How to use help
          • 5.6.2. Translation of docstrings into different languages
          • 5.6.3. How to configure Screen and Turtles
        • 5.7. Demo scripts
      • 6. IDLE
        • 6.1. Menus
          • 6.1.1. File menu (Shell and Editor)
          • 6.1.2. Edit menu (Shell and Editor)
          • 6.1.3. Format menu (Editor window only)
          • 6.1.4. Run menu (Editor window only)
          • 6.1.5. Shell menu (Shell window only)
          • 6.1.6. Debug menu (Shell window only)
          • 6.1.7. Options menu (Shell and Editor)
          • 6.1.8. Window menu (Shell and Editor)
          • 6.1.9. Help menu (Shell and Editor)
          • 6.1.10. Context Menus
        • 6.2. Editing and navigation
          • 6.2.1. Automatic indentation
          • 6.2.2. Completions
          • 6.2.3. Calltips
          • 6.2.4. Python Shell window
          • 6.2.5. Text colors
        • 6.3. Startup and code execution
          • 6.3.1. Command line usage
          • 6.3.2. IDLE-console differences
          • 6.3.3. Running without a subprocess
        • 6.4. Help and preferences
          • 6.4.1. Additional help sources
          • 6.4.2. Setting preferences
          • 6.4.3. Extensions
      • 7. Other Graphical User Interface Packages
    • 25 Development Tools
      • 1. pydoc — Documentation generator and online help system
      • 2. doctest — Test interactive Python examples
        • 2.1. Simple Usage: Checking Examples in Docstrings
        • 2.2. Simple Usage: Checking Examples in a Text File
        • 2.3. How It Works
          • 2.3.1. Which Docstrings Are Examined?
          • 2.3.2. How are Docstring Examples Recognized?
          • 2.3.3. What’s the Execution Context?
          • 2.3.4. What About Exceptions?
          • 2.3.5. Option Flags
          • 2.3.6. Directives
          • 2.3.7. Warnings
        • 2.4. Basic API
        • 2.5. Unittest API
        • 2.6. Advanced API
          • 2.6.1. DocTest Objects
          • 2.6.2. Example Objects
          • 2.6.3. DocTestFinder objects
          • 2.6.4. DocTestParser objects
          • 2.6.5. DocTestRunner objects
          • 2.6.6. OutputChecker objects
        • 2.7. Debugging
        • 2.8. Soapbox
      • 3. unittest — Unit testing framework
        • 3.1. Basic example
        • 3.2. Command-Line Interface
          • 3.2.1. Command-line options
        • 3.3. Test Discovery
        • 3.4. Organizing test code
        • 3.5. Re-using old test code
        • 3.6. Skipping tests and expected failures
        • 3.7. Classes and functions
          • 3.7.1. Test cases
            • 3.7.1.1. Deprecated aliases
          • 3.7.2. Grouping tests
          • 3.7.3. Loading and running tests
            • 3.7.3.1. load_tests Protocol
        • 3.8. Class and Module Fixtures
          • 3.8.1. setUpClass and tearDownClass
          • 3.8.2. setUpModule and tearDownModule
        • 3.9. Signal Handling
      • 4. 2to3 - Automated Python 2 to 3 code translation
        • 4.1. Using 2to3
        • 4.2. Fixers
        • 4.3. lib2to3 - 2to3’s library
      • 5. test — Regression tests package for Python
        • 5.1. Writing Unit Tests for the test package
        • 5.2. Running tests using the command-line interface
      • 6. test.test_support — Utility functions for tests
  • Ch 26 - 30
    • 26. Debugging and Profiling
      • 1. bdb — Debugger framework
      • 2. pdb — The Python Debugger
        • 2.1. Debugger Commands
      • 3. cProfile, profile — The Python Profilers
        • 3.1. Introduction to the profilers
        • 3.2. Instant User’s Manual
        • 3.3. profile and cProfile Module Reference
        • 3.4. The Stats Class
        • 3.5. What Is Deterministic Profiling?
        • 3.6. Limitations
        • 3.7. Calibration
        • 3.8. Using a custom timer
      • 4. hotshot — High performance logging profiler
        • 4.1. Profile Objects
        • 4.2. Using hotshot data
        • 4.3. Example Usage
      • 5. timeit — Measure execution time of small code snippets
        • 5.1. Basic Examples
        • 5.2. Python Interface
        • 5.3. Command-Line Interface
        • 5.4. Examples
      • 6. trace — Trace or track Python statement execution
        • 6.1. Command-Line Usage
          • 6.1.1. Main options
          • 6.1.2. Modifiers
          • 6.1.3. Filters
        • 6.2. Programmatic Interface
    • 27 Software Packaging and Distribution
      • 1. distutils — Building and installing Python modules
      • 2. ensurepip — Bootstrapping the pip installer
        • 2.1. Command line interface
        • 2.2. Module API
    • 28 Python Runtime Services
      • 1. sys — System-specific parameters and functions
      • 2. sysconfig — Provide access to Python’s configuration information
        • 2.1. Configuration variables
        • 2.2. Installation paths
        • 2.3. Other functions
      • 3. __builtin__ — Built-in objects
      • 4. future_builtins — Python 3 builtins
      • 5. __main__ — Top-level script environment
      • 6. warnings — Warning control
        • 6.1. Warning Categories
        • 6.2. The Warnings Filter
          • 6.2.1. Default Warning Filters
        • 6.3. Temporarily Suppressing Warnings
        • 6.4. Testing Warnings
        • 6.5. Updating Code For New Versions of Python
        • 6.6. Available Functions
        • 6.7. Available Context Managers
      • 7. contextlib — Utilities for with-statement contexts
      • 8. abc — Abstract Base Classes
      • 9. atexit — Exit handlers
        • 9.1. atexit Example
      • 10. traceback — Print or retrieve a stack traceback
        • 10.1. Traceback Examples
      • 11. __future__ — Future statement definitions
      • 12. gc — Garbage Collector interface
      • 13. inspect — Inspect live objects
        • 13.1. Types and members
        • 13.2. Retrieving source code
        • 13.3. Classes and functions
        • 13.4. The interpreter stack
      • 14. site — Site-specific configuration hook
      • 15. user — User-specific configuration hook
      • 16. fpectl — Floating point exception control
        • 16.1. Example
        • 16.2. Limitations and other considerations
    • 29 Custom Python Interpreters
      • 1. code — Interpreter base classes
        • 1.1. Interactive Interpreter Objects
        • 1.2. Interactive Console Objects
      • 2. codeop — Compile Python code
    • 30 Restricted Execution
      • 1. rexec — Restricted execution framework
        • 1.1. RExec Objects
        • 1.2. Defining restricted environments
        • 1.3. An example
      • 2. Bastion — Restricting access to objects
  • Ch 31 - 37
    • 31 Importing Modules
      • 1. imp — Access the import internals
        • 1.1. Examples
      • 2. importlib – Convenience wrappers for __import__()
      • 3. (depr) imputil — Import utilities
        • 3.1. Examples
      • 4. zipimport — Import modules from Zip archives
        • 4.1. zipimporter Objects
        • 4.2. Examples
      • 5. pkgutil — Package extension utility
      • 6. modulefinder — Find modules used by a script
        • 6.1. Example usage of ModuleFinder
      • 7. runpy — Locating and executing Python modules
    • 32 Python Language Services
      • 1. parser — Access Python parse trees
        • 1.1. Creating ST Objects
        • 1.2. Converting ST Objects
        • 1.3. Queries on ST Objects
        • 1.4. Exceptions and Error Handling
        • 1.5. ST Objects
        • 1.6. Example: Emulation of compile()
      • 2. ast — Abstract Syntax Trees
        • 2.1. Node classes
        • 2.2. Abstract Grammar
        • 2.3. ast Helpers
      • 3. symtable — Access to the compiler’s symbol tables
        • 3.1. Generating Symbol Tables
        • 3.2. Examining Symbol Tables
      • 4. symbol — Constants used with Python parse trees
      • 5. token — Constants used with Python parse trees
      • 6. keyword — Testing for Python keywords
      • 7. tokenize — Tokenizer for Python source
      • 8. tabnanny — Detection of ambiguous indentation
      • 9. pyclbr — Python class browser support
        • 9.1. Class Objects
        • 9.2. Function Objects
      • 10. py_compile — Compile Python source files
      • 11. compileall — Byte-compile Python libraries
        • 11.1. Command-line use
        • 11.2. Public functions
      • 12. dis — Disassembler for Python bytecode
        • 12.1. Python Bytecode Instructions
      • 13. pickletools — Tools for pickle developers
    • 33 (depr) Python compiler package
      • The basic interface
      • Limitations
      • Python Abstract Syntax
        • AST Nodes
        • Assignment nodes
        • Examples
      • Using Visitors to Walk ASTs
      • Bytecode Generation
    • 34. Miscellaneous Services
      • 1. formatter — Generic output formatting
        • 1.1. The Formatter Interface
        • 1.2. Formatter Implementations
        • 1.3. The Writer Interface
        • 1.4. Writer Implementations
    • 35 MS Windows Specific Services
      • 1. msilib — Read and write Microsoft Installer files
        • 1.1. Database Objects
        • 1.2. View Objects
        • 1.3. Summary Information Objects
        • 1.4. Record Objects
        • 1.5. Errors
        • 1.6. CAB Objects
        • 1.7. Directory Objects
        • 1.8. Features
        • 1.9. GUI classes
        • 1.10. Precomputed tables
      • 2. msvcrt – Useful routines from the MS VC++ runtime
        • 2.1. File Operations
        • 2.2. Console I/O
        • 2.3. Other Functions
      • 3. _winreg – Windows registry access
        • 3.1. Constants
          • 3.1.1. HKEY_* Constants
          • 3.1.2. Access Rights
            • 3.1.2.1. 64-bit Specific
          • 3.1.3. Value Types
        • 3.2. Registry Handle Objects
      • 4. winsound — Sound-playing interface for Windows
    • 36. Unix Specific Services
      • 1. posix — The most common POSIX system calls
        • 1.1. Large File Support
        • 1.2. Notable Module Contents
      • 2. pwd — The password database
      • 3. spwd — The shadow password database
      • 4. grp — The group database
      • 5. crypt — Function to check Unix passwords
      • 6. (deprecated) dl — Call C functions in shared objects
        • 6.1. Dl Objects
      • 7. termios — POSIX style tty control
        • 7.1. Example
      • 8. tty — Terminal control functions
      • 9. pty — Pseudo-terminal utilities
      • 10. fcntl — The fcntl and ioctl system calls
      • 11. pipes — Interface to shell pipelines
        • 11.1. Template Objects
      • 12. posixfile — File-like objects with locking support
      • 13. resource — Resource usage information
        • 13.1. Resource Limits
        • 13.2. Resource Usage
      • 14. nis — Interface to Sun’s NIS (Yellow Pages)
      • 15. syslog — Unix syslog library routines
        • 15.1. Examples
          • 15.1.1. Simple example
      • 16. (deprecated) commands — Utilities for running commands
    • 37 Mac OS X specific services
      • 1. ic — Access to the Mac OS X Internet Config
        • 1.1. IC Objects
      • 2. MacOS — Access to Mac OS interpreter features
      • 3. macostools — Convenience routines for file manipulation
      • 4. findertools — The finder‘s Apple Events interface
      • 5. EasyDialogs — Basic Macintosh dialogs
        • 5.1. ProgressBar Objects
      • 6. FrameWork — Interactive application framework
        • 6.1. Application Objects
        • 6.2. Window Objects
        • 6.3. ControlsWindow Object
        • 6.4. ScrolledWindow Object
        • 6.5. DialogWindow Objects
      • 7. autoGIL — Global Interpreter Lock handling in event loops
      • 8. Mac OS Toolbox Modules
        • 8.1. Carbon.AE — Apple Events
        • 8.2. Carbon.AH — Apple Help
        • 8.3. Carbon.App — Appearance Manager
        • 8.4. Carbon.Appearance — Appearance Manager constants
        • 8.5. Carbon.CF — Core Foundation
        • 8.6. Carbon.CG — Core Graphics
        • 8.7. Carbon.CarbonEvt — Carbon Event Manager
        • 8.8. Carbon.CarbonEvents — Carbon Event Manager constants
        • 8.9. Carbon.Cm — Component Manager
        • 8.10. Carbon.Components — Component Manager constants
        • 8.11. Carbon.ControlAccessor — Control Manager accssors
        • 8.12. Carbon.Controls — Control Manager constants
        • 8.13. Carbon.CoreFounation — CoreFounation constants
        • 8.14. Carbon.CoreGraphics — CoreGraphics constants
        • 8.15. Carbon.Ctl — Control Manager
        • 8.16. Carbon.Dialogs — Dialog Manager constants
        • 8.17. Carbon.Dlg — Dialog Manager
        • 8.18. Carbon.Drag — Drag and Drop Manager
        • 8.19. Carbon.Dragconst — Drag and Drop Manager constants
        • 8.20. Carbon.Events — Event Manager constants
        • 8.21. Carbon.Evt — Event Manager
        • 8.22. Carbon.File — File Manager
        • 8.23. Carbon.Files — File Manager constants
        • 8.24. Carbon.Fm — Font Manager
        • 8.25. Carbon.Folder — Folder Manager
        • 8.26. Carbon.Folders — Folder Manager constants
        • 8.27. Carbon.Fonts — Font Manager constants
        • 8.28. Carbon.Help — Help Manager
        • 8.29. Carbon.IBCarbon — Carbon InterfaceBuilder
        • 8.30. Carbon.IBCarbonRuntime — Carbon InterfaceBuilder constants
        • 8.31. Carbon.Icn — Carbon Icon Manager
        • 8.32. Carbon.Icons — Carbon Icon Manager constants
        • 8.33. Carbon.Launch — Carbon Launch Services
        • 8.34. Carbon.LaunchServices — Carbon Launch Services constants
        • 8.35. Carbon.List — List Manager
        • 8.36. Carbon.Lists — List Manager constants
        • 8.37. Carbon.MacHelp — Help Manager constants
        • 8.38. Carbon.MediaDescr — Parsers and generators for Quicktime Media descriptors
        • 8.39. Carbon.Menu — Menu Manager
        • 8.40. Carbon.Menus — Menu Manager constants
        • 8.41. Carbon.Mlte — MultiLingual Text Editor
        • 8.42. Carbon.OSA — Carbon OSA Interface
        • 8.43. Carbon.OSAconst — Carbon OSA Interface constants
        • 8.44. Carbon.QDOffscreen — QuickDraw Offscreen constants
        • 8.45. Carbon.Qd — QuickDraw
        • 8.46. Carbon.Qdoffs — QuickDraw Offscreen
        • 8.47. Carbon.Qt — QuickTime
        • 8.48. Carbon.QuickDraw — QuickDraw constants
        • 8.49. Carbon.QuickTime — QuickTime constants
        • 8.50. Carbon.Res — Resource Manager and Handles
        • 8.51. Carbon.Resources — Resource Manager and Handles constants
        • 8.52. Carbon.Scrap — Scrap Manager
        • 8.53. Carbon.Snd — Sound Manager
        • 8.54. Carbon.Sound — Sound Manager constants
        • 8.55. Carbon.TE — TextEdit
        • 8.56. Carbon.TextEdit — TextEdit constants
        • 8.57. Carbon.Win — Window Manager
        • 8.58. Carbon.Windows — Window Manager constants
      • 9. ColorPicker — Color selection dialog
Python Standard Library Doc
  • Docs »
  • Ch 16 - 20 »
  • 20b Internet Protocols and Support »
  • 8. cookielib — Cookie handling for HTTP clients
  • View page source

8. cookielib — Cookie handling for HTTP clients¶

Contents

  • CookieJar and FileCookieJar Objects
  • FileCookieJar subclasses and co-operation with web browsers
  • CookiePolicy Objects
  • DefaultCookiePolicy Objects
  • Cookie Objects
  • Examples

Note

The cookielib module has been renamed to http.cookiejar in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

New in version 2.4.


The cookielib module defines classes for automatic handling of HTTP cookies. It is useful for accessing web sites that require small pieces of data – cookies – to be set on the client machine by an HTTP response from a web server, and then returned to the server in later HTTP requests.

Both the regular Netscape cookie protocol and the protocol defined by RFC 2965 are handled. RFC 2965 handling is switched off by default. RFC 2109 cookies are parsed as Netscape cookies and subsequently treated either as Netscape or RFC 2965 cookies according to the ‘policy’ in effect. Note that the great majority of cookies on the Internet are Netscape cookies. cookielib attempts to follow the de-facto Netscape cookie protocol (which differs substantially from that set out in the original Netscape specification), including taking note of the max-age and port cookie-attributes introduced with RFC 2965.

Note

The various named parameters found in Set-Cookie and Set-Cookie2 headers (eg. domain and expires) are conventionally referred to as attributes. To distinguish them from Python attributes, the documentation for this module uses the term cookie-attribute instead.

The module defines the following exception:

exception cookielib.LoadError[source]¶

Instances of FileCookieJar raise this exception on failure to load cookies from a file.

Note

For backwards-compatibility with Python 2.4 (which raised an IOError), LoadError is a subclass of IOError.

The following classes are provided:

class cookielib.CookieJar(policy=None)[source]¶

policy is an object implementing the CookiePolicy interface.

The CookieJar class stores HTTP cookies. It extracts cookies from HTTP requests, and returns them in HTTP responses. CookieJar instances automatically expire contained cookies when necessary. Subclasses are also responsible for storing and retrieving cookies from a file or database.

class cookielib.FileCookieJar(filename, delayload=None, policy=None)[source]¶

policy is an object implementing the CookiePolicy interface. For the other arguments, see the documentation for the corresponding attributes.

A CookieJar which can load cookies from, and perhaps save cookies to, a file on disk. Cookies are NOT loaded from the named file until either the load() or revert() method is called. Subclasses of this class are documented in section FileCookieJar subclasses and co-operation with web browsers.

class cookielib.CookiePolicy[source]¶

This class is responsible for deciding whether each cookie should be accepted from / returned to the server.

class cookielib.DefaultCookiePolicy(blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal, strict_ns_set_initial_dollar=False, strict_ns_set_path=False)[source]¶

Constructor arguments should be passed as keyword arguments only. blocked_domains is a sequence of domain names that we never accept cookies from, nor return cookies to. allowed_domains if not None, this is a sequence of the only domains for which we accept and return cookies. For all other arguments, see the documentation for CookiePolicy and DefaultCookiePolicy objects.

DefaultCookiePolicy implements the standard accept / reject rules for Netscape and RFC 2965 cookies. By default, RFC 2109 cookies (ie. cookies received in a Set-Cookie header with a version cookie-attribute of 1) are treated according to the RFC 2965 rules. However, if RFC 2965 handling is turned off or rfc2109_as_netscape is True, RFC 2109 cookies are ‘downgraded’ by the CookieJar instance to Netscape cookies, by setting the version attribute of the Cookie instance to 0. DefaultCookiePolicy also provides some parameters to allow some fine-tuning of policy.

class cookielib.Cookie[source]¶

This class represents Netscape, RFC 2109 and RFC 2965 cookies. It is not expected that users of cookielib construct their own Cookie instances. Instead, if necessary, call make_cookies() on a CookieJar instance.

See also

Module urllib2
URL opening with automatic cookie handling.
Module Cookie
HTTP cookie classes, principally useful for server-side code. The cookielib and Cookie modules do not depend on each other.
https://curl.haxx.se/rfc/cookie_spec.html
The specification of the original Netscape cookie protocol. Though this is still the dominant protocol, the ‘Netscape cookie protocol’ implemented by all the major browsers (and cookielib) only bears a passing resemblance to the one sketched out in cookie_spec.html.
RFC 2109 - HTTP State Management Mechanism
Obsoleted by RFC 2965. Uses Set-Cookie with version=1.
RFC 2965 - HTTP State Management Mechanism
The Netscape protocol with the bugs fixed. Uses Set-Cookie2 in place of Set-Cookie. Not widely used.
http://kristol.org/cookie/errata.html
Unfinished errata to RFC 2965.

RFC 2964 - Use of HTTP State Management

8.1. CookieJar and FileCookieJar Objects¶

CookieJar objects support the iterator protocol for iterating over contained Cookie objects.

CookieJar has the following methods:

CookieJar.add_cookie_header(request)[source]¶

Add correct Cookie header to request.

If policy allows (ie. the rfc2965 and hide_cookie2 attributes of the CookieJar‘s CookiePolicy instance are true and false respectively), the Cookie2 header is also added when appropriate.

The request object (usually a urllib2.Request instance) must support the methods get_full_url(), get_host(), get_type(), unverifiable(), get_origin_req_host(), has_header(), get_header(), header_items(), and add_unredirected_header(),as documented by urllib2.

CookieJar.extract_cookies(response, request)[source]¶

Extract cookies from HTTP response and store them in the CookieJar, where allowed by policy.

The CookieJar will look for allowable Set-Cookie and Set-Cookie2 headers in the response argument, and store cookies as appropriate (subject to the CookiePolicy.set_ok() method’s approval).

The response object (usually the result of a call to urllib2.urlopen(), or similar) should support an info() method, which returns an object with a getallmatchingheaders() method (usually a mimetools.Message instance).

The request object (usually a urllib2.Request instance) must support the methods get_full_url(), get_host(), unverifiable(), and get_origin_req_host(), as documented by urllib2. The request is used to set default values for cookie-attributes as well as for checking that the cookie is allowed to be set.

CookieJar.set_policy(policy)[source]¶

Set the CookiePolicy instance to be used.

CookieJar.make_cookies(response, request)[source]¶

Return sequence of Cookie objects extracted from response object.

See the documentation for extract_cookies() for the interfaces required of the response and request arguments.

CookieJar.set_cookie_if_ok(cookie, request)[source]¶

Set a Cookie if policy says it’s OK to do so.

CookieJar.set_cookie(cookie)[source]¶

Set a Cookie, without checking with policy to see whether or not it should be set.

CookieJar.clear([domain[, path[, name]]])[source]¶

Clear some cookies.

If invoked without arguments, clear all cookies. If given a single argument, only cookies belonging to that domain will be removed. If given two arguments, cookies belonging to the specified domain and URL path are removed. If given three arguments, then the cookie with the specified domain, path and name is removed.

Raises KeyError if no matching cookie exists.

CookieJar.clear_session_cookies()[source]¶

Discard all session cookies.

Discards all contained cookies that have a true discard attribute (usually because they had either no max-age or expires cookie-attribute, or an explicit discard cookie-attribute). For interactive browsers, the end of a session usually corresponds to closing the browser window.

Note that the save() method won’t save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument.

FileCookieJar implements the following additional methods:

FileCookieJar.save(filename=None, ignore_discard=False, ignore_expires=False)[source]¶

Save cookies to a file.

This base class raises NotImplementedError. Subclasses may leave this method unimplemented.

filename is the name of file in which to save cookies. If filename is not specified, self.filename is used (whose default is the value passed to the constructor, if any); if self.filename is None, ValueError is raised.

ignore_discard: save even cookies set to be discarded. ignore_expires: save even cookies that have expired

The file is overwritten if it already exists, thus wiping all the cookies it contains. Saved cookies can be restored later using the load() or revert() methods.

FileCookieJar.load(filename=None, ignore_discard=False, ignore_expires=False)[source]¶

Load cookies from a file.

Old cookies are kept unless overwritten by newly loaded ones.

Arguments are as for save().

The named file must be in the format understood by the class, or LoadError will be raised. Also, IOError may be raised, for example if the file does not exist.

Note

For backwards-compatibility with Python 2.4 (which raised an IOError), LoadError is a subclass of IOError.

FileCookieJar.revert(filename=None, ignore_discard=False, ignore_expires=False)[source]¶

Clear all cookies and reload cookies from a saved file.

revert() can raise the same exceptions as load(). If there is a failure, the object’s state will not be altered.

FileCookieJar instances have the following public attributes:

FileCookieJar.filename¶

Filename of default file in which to keep cookies. This attribute may be assigned to.

FileCookieJar.delayload¶

If true, load cookies lazily from disk. This attribute should not be assigned to. This is only a hint, since this only affects performance, not behaviour (unless the cookies on disk are changing). A CookieJar object may ignore it. None of the FileCookieJar classes included in the standard library lazily loads cookies.

8.2. FileCookieJar subclasses and co-operation with web browsers¶

The following CookieJar subclasses are provided for reading and writing.

class cookielib.MozillaCookieJar(filename, delayload=None, policy=None)[source]¶

A FileCookieJar that can load from and save cookies to disk in the Mozilla cookies.txt file format (which is also used by the Lynx and Netscape browsers).

Note

Version 3 of the Firefox web browser no longer writes cookies in the cookies.txt file format.

Note

This loses information about RFC 2965 cookies, and also about newer or non-standard cookie-attributes such as port.

Warning

Back up your cookies before saving if you have cookies whose loss / corruption would be inconvenient (there are some subtleties which may lead to slight changes in the file over a load / save round-trip).

Also note that cookies saved while Mozilla is running will get clobbered by Mozilla.

class cookielib.LWPCookieJar(filename, delayload=None, policy=None)[source]¶

A FileCookieJar that can load from and save cookies to disk in format compatible with the libwww-perl library’s Set-Cookie3 file format. This is convenient if you want to store cookies in a human-readable file.

8.3. CookiePolicy Objects¶

Objects implementing the CookiePolicy interface have the following methods:

CookiePolicy.set_ok(cookie, request)[source]¶

Return boolean value indicating whether cookie should be accepted from server.

cookie is a cookielib.Cookie instance. request is an object implementing the interface defined by the documentation for CookieJar.extract_cookies().

CookiePolicy.return_ok(cookie, request)[source]¶

Return boolean value indicating whether cookie should be returned to server.

cookie is a cookielib.Cookie instance. request is an object implementing the interface defined by the documentation for CookieJar.add_cookie_header().

CookiePolicy.domain_return_ok(domain, request)[source]¶

Return false if cookies should not be returned, given cookie domain.

This method is an optimization. It removes the need for checking every cookie with a particular domain (which might involve reading many files). Returning true from domain_return_ok() and path_return_ok() leaves all the work to return_ok().

If domain_return_ok() returns true for the cookie domain, path_return_ok() is called for the cookie path. Otherwise, path_return_ok() and return_ok() are never called for that cookie domain. If path_return_ok() returns true, return_ok() is called with the Cookie object itself for a full check. Otherwise, return_ok() is never called for that cookie path.

Note that domain_return_ok() is called for every cookie domain, not just for the request domain. For example, the function might be called with both ".example.com" and "www.example.com" if the request domain is "www.example.com". The same goes for path_return_ok().

The request argument is as documented for return_ok().

CookiePolicy.path_return_ok(path, request)[source]¶

Return false if cookies should not be returned, given cookie path.

See the documentation for domain_return_ok().

In addition to implementing the methods above, implementations of the CookiePolicy interface must also supply the following attributes, indicating which protocols should be used, and how. All of these attributes may be assigned to.

CookiePolicy.netscape¶

Implement Netscape protocol.

CookiePolicy.rfc2965¶

Implement RFC 2965 protocol.

CookiePolicy.hide_cookie2¶

Don’t add Cookie2 header to requests (the presence of this header indicates to the server that we understand RFC 2965 cookies).

The most useful way to define a CookiePolicy class is by subclassing from DefaultCookiePolicy and overriding some or all of the methods above. CookiePolicy itself may be used as a ‘null policy’ to allow setting and receiving any and all cookies (this is unlikely to be useful).

8.4. DefaultCookiePolicy Objects¶

Implements the standard rules for accepting and returning cookies.

Both RFC 2965 and Netscape cookies are covered. RFC 2965 handling is switched off by default.

The easiest way to provide your own policy is to override this class and call its methods in your overridden implementations before adding your own additional checks:

import cookielib
class MyCookiePolicy(cookielib.DefaultCookiePolicy):
    def set_ok(self, cookie, request):
        if not cookielib.DefaultCookiePolicy.set_ok(self, cookie, request):
            return False
        if i_dont_want_to_store_this_cookie(cookie):
            return False
        return True

In addition to the features required to implement the CookiePolicy interface, this class allows you to block and allow domains from setting and receiving cookies. There are also some strictness switches that allow you to tighten up the rather loose Netscape protocol rules a little bit (at the cost of blocking some benign cookies).

A domain blacklist and whitelist is provided (both off by default). Only domains not in the blacklist and present in the whitelist (if the whitelist is active) participate in cookie setting and returning. Use the blocked_domains constructor argument, and blocked_domains() and set_blocked_domains() methods (and the corresponding argument and methods for allowed_domains). If you set a whitelist, you can turn it off again by setting it to None.

Domains in block or allow lists that do not start with a dot must equal the cookie domain to be matched. For example, "example.com" matches a blacklist entry of "example.com", but "www.example.com" does not. Domains that do start with a dot are matched by more specific domains too. For example, both "www.example.com" and "www.coyote.example.com" match ".example.com" (but "example.com" itself does not). IP addresses are an exception, and must match exactly. For example, if blocked_domains contains "192.168.1.2" and ".168.1.2", 192.168.1.2 is blocked, but 193.168.1.2 is not.

DefaultCookiePolicy implements the following additional methods:

DefaultCookiePolicy.blocked_domains()[source]¶

Return the sequence of blocked domains (as a tuple).

DefaultCookiePolicy.set_blocked_domains(blocked_domains)[source]¶

Set the sequence of blocked domains.

DefaultCookiePolicy.is_blocked(domain)[source]¶

Return whether domain is on the blacklist for setting or receiving cookies.

DefaultCookiePolicy.allowed_domains()[source]¶

Return None, or the sequence of allowed domains (as a tuple).

DefaultCookiePolicy.set_allowed_domains(allowed_domains)[source]¶

Set the sequence of allowed domains, or None.

DefaultCookiePolicy.is_not_allowed(domain)[source]¶

Return whether domain is not on the whitelist for setting or receiving cookies.

DefaultCookiePolicy instances have the following attributes, which are all initialised from the constructor arguments of the same name, and which may all be assigned to.

DefaultCookiePolicy.rfc2109_as_netscape¶

If true, request that the CookieJar instance downgrade RFC 2109 cookies (ie. cookies received in a Set-Cookie header with a version cookie-attribute of 1) to Netscape cookies by setting the version attribute of the Cookie instance to 0. The default value is None, in which case RFC 2109 cookies are downgraded if and only if RFC 2965 handling is turned off. Therefore, RFC 2109 cookies are downgraded by default.

New in version 2.5.

General strictness switches:

DefaultCookiePolicy.strict_domain¶

Don’t allow sites to set two-component domains with country-code top-level domains like .co.uk, .gov.uk, .co.nz.etc. This is far from perfect and isn’t guaranteed to work!

RFC 2965 protocol strictness switches:

DefaultCookiePolicy.strict_rfc2965_unverifiable¶

Follow RFC 2965 rules on unverifiable transactions (usually, an unverifiable transaction is one resulting from a redirect or a request for an image hosted on another site). If this is false, cookies are never blocked on the basis of verifiability

Netscape protocol strictness switches:

DefaultCookiePolicy.strict_ns_unverifiable¶

Apply RFC 2965 rules on unverifiable transactions even to Netscape cookies.

DefaultCookiePolicy.strict_ns_domain¶

Flags indicating how strict to be with domain-matching rules for Netscape cookies. See below for acceptable values.

DefaultCookiePolicy.strict_ns_set_initial_dollar¶

Ignore cookies in Set-Cookie: headers that have names starting with '$'.

DefaultCookiePolicy.strict_ns_set_path¶

Don’t allow setting cookies whose path doesn’t path-match request URI.

strict_ns_domain is a collection of flags. Its value is constructed by or-ing together (for example, DomainStrictNoDots|DomainStrictNonDomain means both flags are set).

DefaultCookiePolicy.DomainStrictNoDots¶

When setting cookies, the ‘host prefix’ must not contain a dot (eg. www.foo.bar.com can’t set a cookie for .bar.com, because www.foo contains a dot).

DefaultCookiePolicy.DomainStrictNonDomain¶

Cookies that did not explicitly specify a domain cookie-attribute can only be returned to a domain equal to the domain that set the cookie (eg. spam.example.com won’t be returned cookies from example.com that had no domain cookie-attribute).

DefaultCookiePolicy.DomainRFC2965Match¶

When setting cookies, require a full RFC 2965 domain-match.

The following attributes are provided for convenience, and are the most useful combinations of the above flags:

DefaultCookiePolicy.DomainLiberal¶

Equivalent to 0 (ie. all of the above Netscape domain strictness flags switched off).

DefaultCookiePolicy.DomainStrict¶

Equivalent to DomainStrictNoDots|DomainStrictNonDomain.

8.5. Cookie Objects¶

Cookie instances have Python attributes roughly corresponding to the standard cookie-attributes specified in the various cookie standards. The correspondence is not one-to-one, because there are complicated rules for assigning default values, because the max-age and expires cookie-attributes contain equivalent information, and because RFC 2109 cookies may be ‘downgraded’ by cookielib from version 1 to version 0 (Netscape) cookies.

Assignment to these attributes should not be necessary other than in rare circumstances in a CookiePolicy method. The class does not enforce internal consistency, so you should know what you’re doing if you do that.

Cookie.version¶

Integer or None. Netscape cookies have version 0. RFC 2965 and RFC 2109 cookies have a version cookie-attribute of 1. However, note that cookielib may ‘downgrade’ RFC 2109 cookies to Netscape cookies, in which case version is 0.

Cookie.name¶

Cookie name (a string).

Cookie.value¶

Cookie value (a string), or None.

Cookie.port¶

String representing a port or a set of ports (eg. ‘80’, or ‘80,8080’), or None.

Cookie.path¶

Cookie path (a string, eg. '/acme/rocket_launchers').

Cookie.secure¶

True if cookie should only be returned over a secure connection.

Cookie.expires¶

Integer expiry date in seconds since epoch, or None. See also the is_expired() method.

Cookie.discard¶

True if this is a session cookie.

Cookie.comment¶

String comment from the server explaining the function of this cookie, or None.

Cookie.comment_url¶

URL linking to a comment from the server explaining the function of this cookie, or None.

Cookie.rfc2109¶

True if this cookie was received as an RFC 2109 cookie (ie. the cookie arrived in a Set-Cookie header, and the value of the Version cookie-attribute in that header was 1). This attribute is provided because cookielib may ‘downgrade’ RFC 2109 cookies to Netscape cookies, in which case version is 0.

New in version 2.5.

Cookie.port_specified¶

True if a port or set of ports was explicitly specified by the server (in the Set-Cookie / Set-Cookie2 header).

Cookie.domain_specified¶

True if a domain was explicitly specified by the server.

Cookie.domain_initial_dot¶

True if the domain explicitly specified by the server began with a dot ('.').

Cookies may have additional non-standard cookie-attributes. These may be accessed using the following methods:

Cookie.has_nonstandard_attr(name)[source]¶

Return true if cookie has the named cookie-attribute.

Cookie.get_nonstandard_attr(name, default=None)[source]¶

If cookie has the named cookie-attribute, return its value. Otherwise, return default.

Cookie.set_nonstandard_attr(name, value)[source]¶

Set the value of the named cookie-attribute.

The Cookie class also defines the following method:

Cookie.is_expired([now=None])[source]¶

True if cookie has passed the time at which the server requested it should expire. If now is given (in seconds since the epoch), return whether the cookie has expired at the specified time.

8.6. Examples¶

The first example shows the most common usage of cookielib:

import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx cookies (assumes Unix/Netscape convention for location of the cookies file):

import os, cookielib, urllib2
cj = cookielib.MozillaCookieJar()
cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt"))
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

The next example illustrates the use of DefaultCookiePolicy. Turn on RFC 2965 cookies, be more strict about domains when setting and returning Netscape cookies, and block some domains from setting cookies or having them returned:

import urllib2
from cookielib import CookieJar, DefaultCookiePolicy
policy = DefaultCookiePolicy(
    rfc2965=True, strict_ns_domain=DefaultCookiePolicy.DomainStrict,
    blocked_domains=["ads.net", ".ads.net"])
cj = CookieJar(policy)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
Next Previous

© Copyright 2016.

Built with Sphinx using a theme provided by Read the Docs.