100% found this document useful (1 vote)
23 views

[Ebooks PDF] download Beginning Python Programmer to Programmer 1st Edition Peter C. Norton full chapters

Peter

Uploaded by

roethfolano1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
23 views

[Ebooks PDF] download Beginning Python Programmer to Programmer 1st Edition Peter C. Norton full chapters

Peter

Uploaded by

roethfolano1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Visit https://ebookfinal.

com to download the full version and


explore more ebook

Beginning Python Programmer to Programmer 1st


Edition Peter C. Norton

_____ Click the link below to download _____


https://ebookfinal.com/download/beginning-python-
programmer-to-programmer-1st-edition-peter-c-norton/

Explore and download more ebook at ebookfinal.com


Here are some recommended products that might interest you.
You can download now and explore!

Beginning Xcode Programmer to Programmer 1st Edition James


Bucanek

https://ebookfinal.com/download/beginning-xcode-programmer-to-
programmer-1st-edition-james-bucanek/

ebookfinal.com

Beginning SharePoint 2007 Building Team Solutions with


MOSS 2007 Programmer to Programmer 1st Edition Amanda
Murphy
https://ebookfinal.com/download/beginning-sharepoint-2007-building-
team-solutions-with-moss-2007-programmer-to-programmer-1st-edition-
amanda-murphy/
ebookfinal.com

Professional Python Frameworks Web 2 0 Programming with


Django and Turbogears Programmer to Programmer 1st Edition
Moore
https://ebookfinal.com/download/professional-python-frameworks-
web-2-0-programming-with-django-and-turbogears-programmer-to-
programmer-1st-edition-moore/
ebookfinal.com

Beginning XSLT and XPath Transforming XML Documents and


Data Wrox Programmer to Programmer 1st Edition Ian
Williams
https://ebookfinal.com/download/beginning-xslt-and-xpath-transforming-
xml-documents-and-data-wrox-programmer-to-programmer-1st-edition-ian-
williams/
ebookfinal.com
Professional Python Frameworks Web 2 0 Programming with
Django and Turbogears Programmer to Programmer 1st Edition
Dana Moore
https://ebookfinal.com/download/professional-python-frameworks-
web-2-0-programming-with-django-and-turbogears-programmer-to-
programmer-1st-edition-dana-moore/
ebookfinal.com

Silverlight 3 Programmer s Reference Wrox Programmer to


Programmer 1st Edition J. Ambrose Little

https://ebookfinal.com/download/silverlight-3-programmer-s-reference-
wrox-programmer-to-programmer-1st-edition-j-ambrose-little/

ebookfinal.com

Professional Windows PowerShell Programmer to Programmer


1st Edition Andrew Watt

https://ebookfinal.com/download/professional-windows-powershell-
programmer-to-programmer-1st-edition-andrew-watt/

ebookfinal.com

Professional Ruby on Rails Programmer to Programmer 1st


Edition Noel Rappin

https://ebookfinal.com/download/professional-ruby-on-rails-programmer-
to-programmer-1st-edition-noel-rappin/

ebookfinal.com

Functional Programming in C Classic Programming Techniques


for Modern Projects Wrox Programmer to Programmer 1st
Edition Oliver Sturm
https://ebookfinal.com/download/functional-programming-in-c-classic-
programming-techniques-for-modern-projects-wrox-programmer-to-
programmer-1st-edition-oliver-sturm/
ebookfinal.com
Beginning Python Programmer to Programmer 1st
Edition Peter C. Norton Digital Instant Download
Author(s): Peter C. Norton
ISBN(s): 9780764596544, 0764596543
Edition: 1
File Details: PDF, 3.90 MB
Year: 2005
Language: english
Beginning Python

Peter Norton, Alex Samuel, David Aitel, Eric Foster-Johnson,


Leonard Richardson, Jason Diamond,
Aleatha Parker, Michael Roberts
Beginning Python
Beginning Python

Peter Norton, Alex Samuel, David Aitel, Eric Foster-Johnson,


Leonard Richardson, Jason Diamond,
Aleatha Parker, Michael Roberts
Beginning Python
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com

Copyright © 2005 by Wiley Publishing, Inc., Indianapolis, Indiana


Published simultaneously in Canada
ISBN-10: 0-7645-9654-3
ISBN-13: 978-0-7645-9654-4
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1B/SQ/QX/QV/IN
Library of Congress Cataloging-in-Publication Data:
Beginning Python / Peter Norton.
p. cm.
Includes bibliographical references and index.
ISBN-13: 978-0-7645-9654-4 (paper/website)
ISBN-10: 0-7645-9654-3 (paper/website)
1. Python (Computer program language) I. Norton, Peter, 1974-
QA76.73.P98B45 2005
005.13’3--dc22
2005013968
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of
the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA
01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal
Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or
online at http://www.wiley.com/go/permissions.

LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESEN-
TATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF
THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WAR-
RANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY
SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUIT-
ABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT
ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL
ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT.
NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE
FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A
POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER
ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT
MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY
HAVE CHANGED OR DISAPPEARED BETWEEN THEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.

For general information on our other products and services please contact our Customer Care Department within the
United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trade-
marks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries,
and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley
Publishing, Inc., is not associated with any product or vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available
in electronic books.
About the Authors
Peter Norton (NY, NY) has been working with Unix and Linux for over a decade at companies large and
small solving problems with Linux. An officer of the NY Linux Users Group, he can be found on the
nylug-talk mailing list. Peter coauthored Professional RHEL3. He works for a very large financial com-
pany in NYC, plying his Python and open-source skills.

Alex Samuel (San Diego, CA) has developed software for biology researchers and now studies high-
energy physics at Caltech. Alex has worked on many GNU/Linux development tools, including GCC,
and co-founded CodeSourcery LLC, a consulting firm specializing in GNU/Linux development tools.

David Aitel (NY, NY) is the CEO of Immunity and a coauthor of Shellcoder’s Handbook.

Eric Foster-Johnson (Minneapolis, MN) uses Python extensively with Java, and is a veteran author,
most recently completing Beginning Shell Scripting.

Leonard Richardson (San Francisco, CA) writes useful Python packages with silly names.

Jason Diamond (CA) Jason Diamond is a software development instructor for DevelopMentor and a
consultant specializing in C++, .NET, Python, and XML. He spends most of his spare time contributing
to open-source projects using his favorite language, Python.

Aleathea Parker (San Francisco CA) is a programmer working as a publication engineer for a major
software company, coding primarily in Python and XSLT. She has a background in web applications and
content management.

Michael Roberts (Puerto Rico) has been programming professionally in C, Perl, and Python for long
enough that Python didn’t actually exist when he started. He is the chief perpetrator of the wftk
open-source workflow toolkit, and he swears that it will someday be finished, for certain values of
“finished”.
Credits
Acquisitions Editor Graphics and Production Specialists
Debra Williams Cauley Sean Decker
Carrie Foster
Development Editor Lauren Goddard
Kelly D. Henthorne Denny Hager
Jennifer Heleine
Production Editor Amanda Spagnuolo
William A. Barton
Quality Control Technicians
Copy Editor Leann Harney
Luann Rouff Joe Niesen
Carl William Pierce
Production Manager
Tim Tate Media Development Specialists
Angela Denny
Editorial Manager Kit Malone
Mary Beth Wakefield Travis Silvers

Vice President & Executive Group Publisher Proofreading and Indexing


Richard Swadley TECHBOOKS Production Services

Vice President and Publisher


Joseph B. Wikert

Project Coordinator
Kristie Rees
To my Claudia, for keeping me thinking straight through a crazy time.
To my mom, Eunice, for bringing me food and asking if I was okay throughout.
To Debra, for roping me into this. And to all of the authors,
I want to thank you for making it to the finish line.
Whoa! I didn’t know what I was getting you all into! —P. N.

To my dad, Clarence A. Johnson, 1922–2005. —E. F-J.

For my mother. —L. R.

For Jilly: 1 = 2. —J. D.

To Aaron, for putting up with me. —A. P.

To my wife, Agnes, in revenge for her doctoral thesis. —M. R.


Contents

Acknowledgments xxix
Introduction xxxi

Chapter 1: Programming Basics and Strings 1


How Programming Is Different from Using a Computer 1
Programming Is Consistency 2
Programming Is Control 2
Programming Copes with Change 2
What All That Means Together 3
The First Steps 3
Starting codeEditor 3
Using codeEditor’s Python Shell 4
Try It Out: Starting the Python Shell 4
Beginning to Use Python — Strings 5
What Is a String? 5
Why the Quotes? 6
Try It Out: Entering Strings with Different Quotes 6
Understanding Different Quotes 6
Putting Two Strings Together 8
Try It Out: Using + to Combine Strings 8
Putting Strings Together in Different Ways 9
Try It Out: Using a Format Specifier to Populate a String 9
Try It Out: More String Formatting 9
Displaying Strings with Print 10
Try It Out: Printing Text with Print 10
Summary 10
Exercises 11

Chapter 2: Numbers and Operators 13


Different Kinds of Numbers 13
Numbers in Python 14
Try It Out: Using Type with Different Numbers 14
Try It Out: Creating an Imaginary Number 15
Contents
Program Files 15
Try It Out: Using the Shell with the Editor 16
Using the Different Types 17
Try It Out Including Different Numbers in Strings 18
Try It Out: Escaping the % Sign in Strings 18
Basic Math 19
Try It Out Doing Basic Math 19
Try It Out: Using the Modulus Operation 20
Some Surprises 20
Try It Out: Printing the Results 21
Using Numbers 21
Order of Evaluation 21
Try It Out: Using Math Operations 21
Number Formats 22
Try It Out: Using Number Formats 22
Mistakes Will Happen 23
Try It Out: Making Mistakes 23
Some Unusual Cases 24
Try It Out: Formatting Numbers as Octal and Hexadecimal 24
Summary 24
Exercises 25

Chapter 3: Variables — Names for Values 27


Referring to Data – Using Names for Data 27
Try It Out: Assigning Values to Names 28
Changing Data Through Names 28
Try It Out: Altering Named Values 29
Copying Data 29
Names You Can’t Use and Some Rules 29
Using More Built-in Types 30
Tuples — Unchanging Sequences of Data 30
Try It Out: Creating and Using a Tuple 30
Try It Out: Accessing a Tuple Through Another Tuple 31
Lists — Changeable Sequences of Data 33
Try It Out Viewing the Elements of a List 33
Dictionaries — Groupings of Data Indexed by Name 34
Try It Out: Making a Dictionary 34
Try It Out: Getting the Keys from a Dictionary 35
Treating a String Like a List 36
Special Types 38

xii
Contents
Other Common Sequence Properties 38
Referencing the Last Elements 38
Ranges of Sequences 39
Try It Out: Slicing Sequences 39
Growing Lists by Appending Sequences 40
Using Lists to Temporarily Store Data 40
Try It Out: Popping Elements from a List 40
Summary 41
Exercises 42

Chapter 4: Making Decisions 43


Comparing Values — Are They the Same? 43
Try It Out: Comparing Values for Sameness 43
Doing the Opposite — Not Equal 45
Try It Out: Comparing Values for Difference 45
Comparing Values — Which One Is More? 45
Try It Out: Comparing Greater Than and Less Than 45
More Than or Equal, Less Than or Equal 47
Reversing True and False 47
Try It Out: Reversing the Outcome of a Test 47
Looking for the Results of More Than One Comparison 48
How to Get Decisions Made 48
Try It Out: Placing Tests within Tests 49
Repetition 51
How to Do Something — Again and Again 51
Try It Out: Using a while Loop 51
Stopping the Repetition 52
Try It Out: Using else While Repeating 54
Try It Out: Using continue to Keep Repeating 54
Handling Errors 55
Trying Things Out 55
Try It Out: Creating an Exception with Its Explanation 56
Summary 57
Exercises 58

Chapter 5: Functions 59
Putting Your Program into Its Own File 59
Try It Out: Run a Program with Python -i 61

xiii
Contents
Functions: Grouping Code under a Name 61
Try It Out: Defining a Function 61
Choosing a Name 62
Describing a Function in the Function 63
Try It Out: Displaying __doc__ 63
The Same Name in Two Different Places 64
Making Notes to Yourself 65
Try It Out: Experimenting with Comments 65
Asking a Function to Use a Value You Provide 66
Try It Out Invoking a Function with Parameters 67
Checking Your Parameters 68
Try It Out: Determining More Types with the type Function 69
Try It Out: Using Strings to Compare Types 69
Setting a Default Value for a Parameter — Just in Case 70
Try It Out: Setting a Default Parameter 70
Calling Functions from within Other Functions 71
Try It Out: Invoking the Completed Function 72
Functions Inside of Functions 72
Flagging an Error on Your Own Terms 73
Layers of Functions 74
How to Read Deeper Errors 74
Summary 75
Exercises 76

Chapter 6: Classes and Objects 79


Thinking About Programming 79
Objects You Already Know 79
Looking Ahead: How You Want to Use Objects 81
Defining a Class 81
How Code Can Be Made into an Object 81
Try It Out: Defining a Class 82
Try It Out: Creating an Object from Your Class 82
Try It Out: Writing an Internal Method 84
Try It Out: Writing Interface Methods 85
Try It Out: Using More Methods 87
Objects and Their Scope 89
Try It Out: Creating Another Class 89
Summary 92
Exercises 93

xiv
Contents

Chapter 7: Organizing Programs 95


Modules 96
Importing a Module So That You Can Use It 96
Making a Module from Pre-existing Code 97
Try It Out: Creating a Module 97
Try It Out: Exploring Your New Module 98
Using Modules — Starting With the Command Line 99
Try It Out: Printing sys.argv 100
Changing How Import Works — Bringing in More 101
Packages 101
Try It Out: Making the Files in the Kitchen Class 102
Modules and Packages 103
Bringing Everything into the Current Scope 103
Try It Out: Exporting Modules from a Package 104
Re-importing Modules and Packages 104
Try It Out: Examining sys.modules 105
Basics of Testing Your Modules and Packages 106
Summary 106
Exercises 107

Chapter 8: Files and Directories 109


File Objects 109
Writing Text Files 110
Reading Text Files 111
Try It Out: Printing the Lengths of Lines in the Sample File 112
File Exceptions 113
Paths and Directories 113
Paths 114
Directory Contents 116
Try It Out: Getting the Contents of a Directory 116
Try It Out: Listing the Contents of Your Desktop or Home Directory 118
Obtaining Information about Files 118
Recursive Directory Listings 118
Renaming, Moving, Copying, and Removing Files 119
Example: Rotating Files 120
Creating and Removing Directories 121
Globbing 122

xv
Contents
Pickles 123
Try It Out: Creating a Pickle File 123
Pickling Tips 124
Efficient Pickling 125
Summary 125
Exercises 125

Chapter 9: Other Features of the Language 127


Lambda and Filter: Short Anonymous Functions 127
Reduce 128
Try It Out: Working with Reduce 128
Map: Short-Circuiting Loops 129
Try It Out: Use Map 129
Decisions within Lists — List Comprehension 130
Generating Lists for Loops 131
Try It Out: Examining an xrange Object 132
Special String Substitution Using Dictionaries 133
Try It Out: String Formatting with Dictionaries 133
Featured Modules 134
Getopt — Getting Options from the Command Line 134
Using More Than One Process 137
Threads — Doing Many Things in the Same Process 139
Storing Passwords 140
Summary 141
Exercises 142

Chapter 10: Building a Module 143


Exploring Modules 143
Importing Modules 145
Finding Modules 145
Digging through Modules 146
Creating Modules and Packages 150
Try It Out: Creating a Module with Functions 150
Working with Classes 151
Defining Object-Oriented Programming 151
Creating Classes 151
Try It Out: Creating a Meal Class 152
Extending Existing Classes 153

xvi
Contents
Finishing Your Modules 154
Defining Module-Specific Errors 154
Choosing What to Export 155
Documenting Your Modules 156
Try It Out: Viewing Module Documentation 157
Testing Your Module 162
Running a Module as a Program 164
Try It Out: Running a Module 164
Creating a Whole Module 165
Try It Out: Finishing a Module 165
Try It Out: Smashing Imports 169
Installing Your Modules 170
Try It Out: Creating an Installable Package 171
Summary 174
Exercises 174

Chapter 11: Text Processing 175


Why Text Processing Is So Useful 175
Searching for Files 176
Clipping Logs 177
Sifting through Mail 178
Navigating the File System with the os Module 178
Try It Out: Listing Files and Playing with Paths 180
Try It Out: Searching for Files of a Particular Type 181
Try It Out: Refining a Search 183
Working with Regular Expressions and the re Module 184
Try It Out: Fun with Regular Expressions 186
Try It Out: Adding Tests 187
Summary 189
Exercises 189

Chapter 12: Testing 191


Assertions 191
Try It Out: Using Assert 192
Test Cases and Test Suites 193
Try It Out: Testing Addition 194
Try It Out: Testing Faulty Addition 195
Test Fixtures 196
Try It Out: Working with Test Fixtures 197

xvii
Contents
Putting It All Together with Extreme Programming 199
Implementing a Search Utility in Python 200
Try It Out: Writing a Test Suite First 201
Try It Out: A General-Purpose Search Framework 203
A More Powerful Python Search 205
Try It Out: Extending the Search Framework 206
Formal Testing in the Software Life Cycle 207
Summary 208

Chapter 13: Writing a GUI with Python 209


GUI Programming Toolkits for Python 209
PyGTK Introduction 210
pyGTK Resources 211
Creating GUI Widgets with pyGTK 213
Try It Out: Writing a Simple pyGTK Program 213
GUI Signals 214
GUI Helper Threads and the GUI Event Queue 216
Try It Out: Writing a Multithreaded pyGTK App 219
Widget Packing 222
Glade: a GUI Builder for pyGTK 223
GUI Builders for Other GUI Frameworks 224
Using libGlade with Python 225
A Glade Walkthrough 225
Starting Glade 226
Creating a Project 227
Using the Palette to Create a Window 227
Putting Widgets into the Window 228
Glade Creates an XML Representation of the GUI 230
Try It Out: Building a GUI from a Glade File 231
Creating a Real Glade Application 231
Advanced Widgets 238
Further Enhancing PyRAP 241
Summary 248
Exercises 248

Chapter 14: Accessing Databases 249


Working with DBM Persistent Dictionaries 250
Choosing a DBM Module 250
Creating Persistent Dictionaries 251
Try It Out: Creating a Persistent Dictionary 251

xviii
Contents
Accessing Persistent Dictionaries 252
Try It Out: Accessing Persistent Dictionaries 253
Deciding When to Use DBM and When to Use a Relational Database 255
Working with Relational Databases 255
Writing SQL Statements 257
Defining Tables 259
Setting Up a Database 260
Try It Out: Creating a Gadfly Database 261
Using the Python Database APIs 262
Downloading Modules 263
Creating Connections 263
Working with Cursors 264
Try It Out: Inserting Records 264
Try It Out: Writing a Simple Query 266
Try It Out: Writing a Complex Join 267
Try It Out: Updating an Employee’s Manager 269
Try It Out: Removing Employees 270
Working with Transactions and Committing the Results 271
Examining Module Capabilities and Metadata 272
Handling Errors 272
Summary 273
Exercises 274

Chapter 15: Using Python for XML 275


What Is XML? 275
A Hierarchical Markup Language 275
A Family of Standards 277
What Is a Schema/DTD? 278
What Are Document Models For? 278
Do You Need One? 278
Document Type Definitions 278
An Example DTD 278
DTDs Aren’t Exactly XML 280
Limitations of DTDs 280
Schemas 280
An Example Schema 280
Schemas Are Pure XML 281
Schemas Are Hierarchical 281
Other Advantages of Schemas 281
Schemas Are Less Widely Supported 281

xix
Contents
XPath 282
HTML as a Subset of XML 282
The HTML DTDs 283
HTMLParser 283
Try It Out: Using HTMLParser 283
htmllib 284
Try It Out: Using htmllib 284
XML Libraries Available for Python 285
Validating XML Using Python 285
What Is Validation? 286
Well-Formedness versus Validation 286
Available Tools 286
Try It Out: Validation Using xmlproc 286
What Is SAX? 287
Stream-based 288
Event-driven 288
What Is DOM? 288
In-memory Access 288
Why Use SAX or DOM 289
Capability Trade-Offs 289
Memory Considerations 289
Speed Considerations 289
SAX and DOM Parsers Available for Python 289
PyXML 290
xml.sax 290
xml.dom.minidom 290
Try It Out: Working with XML Using DOM 290
Try It Out: Working with XML Using SAX 292
Intro to XSLT 293
XSLT Is XML 293
Transformation and Formatting Language 293
Functional, Template-Driven 293
Using Python to Transform XML Using XSLT 294
Try It Out: Transforming XML with XSLT 294
Putting It All Together: Working with RSS 296
RSS Overview and Vocabulary 296
Making Sense of It All 296
RSS Vocabulary 297
An RSS DTD 297

xx
Contents
A Real-World Problem 297
Try It Out: Creating an RSS Feed 298
Creating the Document 300
Checking It Against the DTD 301
Another Real-World Problem 301
Try It Out: Creating An Aggregator 301
Summary 303
Exercises 303

Chapter 16: Network Programming 305


Try It Out: Sending Some E-mail 305
Understanding Protocols 307
Comparing Protocols and Programming Languages 307
The Internet Protocol Stack 308
A Little Bit About the Internet Protocol 309
Internet Addresses 309
Internet Ports 310
Sending Internet E-mail 311
The E-mail File Format 311
MIME Messages 313
MIME Encodings: Quoted-printable and Base64 313
MIME Content Types 314
Try It Out: Creating a MIME Message with an Attachment 315
MIME Multipart Messages 316
Try It Out: Building E-mail Messages with SmartMessage 320
Sending Mail with SMTP and smtplib 321
Try It Out: Sending Mail with MailServer 323
Retrieving Internet E-mail 323
Parsing a Local Mail Spool with mailbox 323
Try It Out: Printing a Summary of Your Mailbox 324
Fetching Mail from a POP3 Server with poplib 325
Try It Out: Printing a Summary of Your POP3 Mailbox 327
Fetching Mail from an IMAP Server with imaplib 327
Try It Out: Printing a Summary of Your IMAP Mailbox 329
IMAP’s Unique Message IDs 330
Try It Out: Fetching a Message by Unique ID 330
Secure POP3 and IMAP 331
Webmail Applications Are Not E-mail Applications 331
Socket Programming 331
Introduction to Sockets 332
Try It Out: Connecting to the SuperSimpleSocketServer with Telnet 333

xxi
Contents
Binding to an External Hostname 334
The Mirror Server 335
Try It Out: Mirroring Text with the MirrorServer 336
The Mirror Client 336
SocketServer 337
Multithreaded Servers 339
The Python Chat Server 340
Design of the Python Chat Server 340
The Python Chat Server Protocol 341
Our Hypothetical Protocol in Action 341
Initial Connection 342
Chat Text 342
Server Commands 342
General Guidelines 343
The Python Chat Client 346
Single-Threaded Multitasking with select 348
Other Topics 350
Miscellaneous Considerations for Protocol Design 350
Trusted Servers 350
Terse Protocols 350
The Twisted Framework 351
Deferred Objects 351
The Peer-to-Peer Architecture 354
Summary 354
Exercises 354

Chapter 17: Extension Programming with C 355


Extension Module Outline 356
Building and Installing Extension Modules 358
Passing Parameters from Python to C 360
Returning Values from C to Python 363
The LAME Project 364
The LAME Extension Module 368
Using Python Objects from C Code 380
Summary 383
Exercises 383

Chapter 18: Writing Shareware and Commercial Programs 385


A Case Study: Background 385
How Much Python Should You Use? 386

xxii
Contents
Pure Python Licensing 387
Web Services Are Your Friend 388
Pricing Strategies 389
Watermarking 390
Other Models 394
Selling as a Platform, Rather Than a Product 395
Your Development Environment 395
Finding Python Programmers 396
Training non-Python Programmers 397
Python Employment Resources 397
Python Problems 397
Porting to Other Versions of Python 397
Porting to Other Operating Systems 398
Debugging Threads 399
Common Gotchas 399
Portable Distribution 400
Essential Libraries 401
Timeoutsocket 401
PyGTK 402
GEOip 402
Summary 403

Chapter 19: Numerical Programming 405


Numbers in Python 405
Integers 406
Long Integers 406
Floating-point Numbers 407
Formatting Numbers 408
Characters as Numbers 410
Mathematics 412
Arithmetic 412
Built-in Math Functions 414
The math Module 415
Complex Numbers 416
Arrays 418
The array Module 420
The numarray Package 422
Using Arrays 422
Computing the Standard Deviation 423
Summary 424
Exercises 425

xxiii
Contents
Chapter 20: Python in the Enterprise 427
Enterprise Applications 428
Document Management 428
The Evolution of Document Management Systems 429
What You Want in a Document Management System 430
People in Directories 431
Taking Action with Workflow 432
Auditing, Sarbanes-Oxley, and What You Need to Know 433
Auditing and Document Management 434
Working with Actual Enterprise Systems 435
Introducing the wftk Workflow Toolkit 435
Try It Out: Very Simple Record Retrieval 436
Try It Out: Very Simple Record Storage 438
Try It Out: Data Storage in MySQL 439
Try It Out: Storing and Retrieving Documents 441
Try It Out: A Document Retention Framework 446
The python-ldap Module 448
Try It Out: Using Basic OpenLDAP Tools 449
Try It Out: Simple LDAP Search 451
More LDAP 453
Back to the wftk 453
Try It Out: Simple Workflow Trigger 454
Try It Out: Action Queue Handler 456
Summary 458
Exercises 458

Chapter 21: Web Applications and Web Services 459


REST: The Architecture of the Web 460
Characteristics of REST 460
A Distributed Network of Interlinked Documents 461
A Client-Server Architecture 461
Servers Are Stateless 461
Resources 461
Representations 462
REST Operations 462
HTTP: Real-World REST 463
Try It Out: Python’s Three-Line Web Server 463
The Visible Web Server 464
Try It Out: Seeing an HTTP Request and Response 465
The HTTP Request 466
The HTTP Response 467

xxiv
Contents
CGI: Turning Scripts into Web Applications 468
Try It Out: Running a CGI Script 469
The Web Server Makes a Deal with the CGI Script 470
CGI’s Special Environment Variables 471
Accepting User Input through HTML Forms 473
The cgi Module: Parsing HTML Forms 474
Try It Out: Printing Any HTML Form Submission 478
Building a Wiki 480
The BittyWiki Core Library 481
Back-end Storage 481
WikiWords 481
Writing the BittyWiki Core 481
Try It Out: Creating Wiki Pages from an Interactive Python Session 483
The BittyWiki Web Interface 484
Resources 484
Request Structure 484
But Wait — There’s More (Resources) 485
Wiki Markup 486
Web Services 493
How Web Services Work 494
REST Web Services 494
REST Quick Start: Finding Bargains on Amazon.com 495
Try It Out: Peeking at an Amazon Web Services Response 496
Introducing WishListBargainFinder 497
Giving BittyWiki a REST API 500
Wiki Search-and-Replace Using the REST Web Service 503
Try It Out: Wiki Searching and Replacing 507
XML-RPC 508
XML-RPC Quick Start: Get Tech News from Meerkat 509
The XML-RPC Request 511
Representation of Data in XML-RPC 512
The XML-RPC Response 513
If Something Goes Wrong 513
Exposing the BittyWiki API through XML-RPC 514
Try It Out: Manipulating BittyWiki through XML-RPC 517
Wiki Search-and-Replace Using the XML-RPC Web Service 518
SOAP 520
SOAP Quick Start: Surfing the Google API 520
The SOAP Request 522
The SOAP Response 524
If Something Goes Wrong 524

xxv
Contents
Exposing a SOAP Interface to BittyWiki 525
Try It Out: Manipulating BittyWiki through SOAP 526
Wiki Search-and-Replace Using the SOAP Web Service 527
Documenting Your Web Service API 529
Human-Readable API Documentation 529
The BittyWiki REST API Document 529
The BittyWiki XML-RPC API Document 529
The BittyWiki SOAP API Document 530
The XML-RPC Introspection API 530
Try It Out: Using the XML-RPC Introspection API 530
WSDL 531
Try It Out: Manipulating BittyWiki through a WSDL Proxy 533
Choosing a Web Service Standard 534
Web Service Etiquette 535
For Consumers of Web Services 535
For Producers of Web Services 535
Using Web Applications as Web Services 536
A Sampling of Publicly Available
Web Services 536
Summary 538
Exercises 538

Chapter 22: Integrating Java with Python 539


Scripting within Java Applications 540
Comparing Python Implementations 541
Installing Jython 541
Running Jython 542
Running Jython Interactively 542
Try It Out: Running the Jython Interpreter 542
Running Jython Scripts 543
Try It Out Running a Python Script 543
Controlling the jython Script 544
Making Executable Commands 545
Try It Out: Making an Executable Script 546
Running Jython on Your Own 546
Packaging Jython-Based Applications 547
Integrating Java and Jython 547
Using Java Classes in Jython 548
Try It Out: Calling on Java Classes 548
Try It Out: Creating a User Interface from Jython 550
Accessing Databases from Jython 552
Working with the Python DB API 553

xxvi
Contents
Setting Up a Database 554
Try It Out: Create Tables 555
Writing J2EE Servlets in Jython 558
Setting Up an Application Server 559
Adding the PyServlet to an Application Server 560
Extending HttpServlet 561
Try It Out: Writing a Python Servlet 562
Choosing Tools for Jython 564
Testing from Jython 565
Try It Out: Exploring Your Environment with Jython 565
Embedding the Jython Interpreter 566
Calling Jython Scripts from Java 566
Try It Out: Embedding Jython 567
Compiling Python Code to Java 568
Handling Differences between C Python and Jython 569
Summary 570
Exercises 571

Appendix A: Answers to Exercises 573

Appendix B: Online Resources 605

Appendix C: What’s New in Python 2.4 609

Glossary 613

Index 623

xxvii
Acknowledgments

I would like to acknowledge Macktez at www.macktez.com. They’re a great group, and not just for loan-
ing me the Mac. Most of all, thank you to the folks who hack on Python and other great projects so that
everyone else can learn. —Peter Norton

I would like to acknowledge the pyGTK team, the hardworking individuals at Immunity, Inc., and my
wife, Justine. —Dave Aitel

I would like to acknowledge Sumana Harihareswara, Mark A. Hershberger, Danny O’Brien, and Tony
Steidler-Dennison. —Leonard Richardson

The publisher would like to thank the early efforts of Oleg Kolesnikov and Levi Cook, who had to bow
out of the writing process due to personal matters, but who contributed to the overall structure and con-
tent outline.
Introduction

What Is Python?
Python is a programming language that embodies many of the best practices and intentions of other pro-
gramming languages that have been created and refined during the last two decades.

❑ Python is interpreted, which makes it easy to test programs and to use interactively.
❑ Python is object-oriented, which enables you to leverage the work of other programmers and
share your own work with the community at large.
❑ Python is open-source software, so you may use it and deploy it without being concerned about
a single company that owns it one day going out of business or otherwise making the language
unavailable to you.
❑ Python is small; it is a simple language that can be explained to a programmer in a very short
time and can be taught to a new programmer without having to worry about the innumerable
special cases that occur with more complex and involved languages.
❑ Python is extensible; it comes with a set of modules that act as tools that build on the language.
Python can also be extended with libraries that come from other languages such as C. Python
makes this integration simple.
❑ Python is familiar; it incorporates many language features from other languages in a way that
makes it friendly to use if you are already familiar with the languages to which it is similar, such
as Java, C, or Perl. At the same time, these concepts that Python has in common with other lan-
guages makes it possible to move to these other languages with confidence.

The Benefits of Python


Python’s benefits are at least twofold: to the person programming in Python and to the user of programs
written in Python.

Some of the benefits to the programmer are as follows:

❑ Consistency — Python is maintained by a loose organization of people, but the language itself is
changed slowly and with the goal of not breaking anything within the same major version
series (that is, 2.3 to 2.4 will have a minimal impact on existing programs).
❑ Scalability — Projects written in Python have been proven to scale to very large projects as both
the primary language and an auxiliary language.
Introduction
❑ Flexibility — Python can be used to work with libraries and programs written in other pro-
gramming languages so that its interpreter can be used with other languages in a manner that
almost always provides more convenience than the language in which the library or program
was written.
❑ Multiple cooperating implementations — There is more than one Python. Different implemen-
tations enable Python to be specialized for special situations or problems in ways that a one-
size-fits-all approach doesn’t allow.
❑ Interactive interpreter — Python provides an environment that can be used to interact with a
program while it is running, which enables programs to be tested, and their behavior changed,
without having to have an extended cycle in which the application is rebuilt to test theories.

The advantages for people who use code written in Python come naturally from the features that make it
so useful to programmers:

❑ Maintainability — Python’s syntax and the structure that the language provides makes it easier
to maintain and, thus, easier for users to make changes and for application programmers to
respond to the needs of their clients.
❑ Cross-platform — Python exists on many hardware and software platforms, making applica-
tions and tools written in Python more durable to changes in a client environment.
❑ Easy to implement — When a product is written in Python, the entire product, including the
Python interpreter, can be included in a single area of the system. This allows the release to be
better controlled and the stability of the product to rely less on the system it’s installed.

Who This Book Is For


This book is written for users who are computer literate and have reached a point where their desire to
control their computing environment has naturally led to wanting to write their own programs. This
population includes the following groups:

❑ Enterprise users who have found that the increasing trend toward the acceptance of open-source
software has led to the ability to write company-sanctioned programs instead of having to wait
for or hire outside parties for simple tasks or to evaluate the feasibility of solving a problem.
❑ Users who have discovered that Linux, FreeBSD, or other Unix or Unix-like operating systems
provide them with programming tools that they can use, but do not necessarily provide the guid-
ance needed to give a new programmer the tools needed to solve their technological problems.
❑ Students who are learning to program and who need a language that is clear and well defined,
and useful in the sense of being able to create real, usable programs at every level.

The first section of this book covers topics that will be useful for both beginning programmers and inter-
mediate practitioners of the discipline. The second section provides useful code and concepts to give the
reader a starting point in understanding how to solve problems by adding to the information and pro-
grams provided to solve their specific problem.

xxxii
Introduction

What This Book Covers


This book begins with the most basic concepts of the Python programming languages and proceeds to
introduce the core concepts of the language. The main body of the book assumes that the reader already
has an installed version of Python 2.4 (or later). To help with this, Appendix B contains references, and
the web site contains download and installation instructions for Python for Linux, Windows, and
MacOS X.

The initial chapters provide the material discussion of all of the concepts needed to write simple pro-
grams in Python, as well as the understanding to peruse and understand programs written by more
experienced programmers, because it is very important to read other people’s programs when learning
how to program.

The early chapters explain important concepts such as the basic types in Python — strings, lists, tuples,
and dictionaries — and build up to the use of classes and objects, and the structure for larger projects in
modules and packages. In addition, these chapters touch on some of the features and changes in recent
versions of Python.

The latter portion of the book covers a variety of topics that are useful to a broad cross-section of the
computer-using population. The intention is that readers who have covered the basic topics will have
the knowledge to use some of the material in the latter half, while other chapters will be more useful for
the novice who has progressed to an intermediate skill level and for programmers who already under-
stand programming or who already have prior knowledge of the problem being solved and want to
understand how to work on that problem in Python.

How This Book Is Structured


Chapters 1–10 walk the reader through programming in Python using examples in the text and explana-
tions of the concepts being introduced, starting with the assumption of a minimal knowledge of pro-
gramming or Python and proceeding from there, building upon concepts as they are introduced.

Examples are based on the theme of food and serving food, because it is a concept with which everyone
should be familiar. Although these examples are simple, they can be used to understand how to write
programs that accomplish other tasks as well.

❑ Chapter 1 covers using the Python interpreter interactively to become familiar with strings, a
basic data type that almost every program will use heavily to provide information to users and
to create any text that will ever be viewed by a user.
❑ Chapter 2 introduces numbers and the basic numeric types involved in arithmetic and the kind
of simple math that is used in day-to-day life, as well as the mathematical operations that you
can perform with them in Python, such as addition, subtraction, multiplication, and division.
❑ Chapter 3 introduces the concept of variables, which are the names that you use to refer to and
store and manipulate data in your programs.
❑ Chapter 4 covers making decisions based on the conditions of the data in the program. Data ref-
erenced through variables can determine the decisions made at different points in time during
the program, and leveraging that control enables programs to be designed to do their work.

xxxiii
Introduction
❑ Chapter 5 covers functions. Functions are a way of taking groups of code that achieve one or a
few goals and putting them together so that they can be invoked by a name that makes obvious
sense when it is viewed in a program.
❑ Chapter 6 adds the concept of the class and the object to programming with Python. Python is
built around the idea of objects, and is usually thought of as an object-oriented language. A class
is a set of data and functions (although functions, when used specifically as part of a class, are
called methods) that create the definition of an object. An object is the result of a class being
invoked and bound to a name that is, from then on, an independent entity that contains data
and methods that can be used in a program independently of other objects of the same type. The
data and methods of an object are not available in general — they are confined to the object in its
scope.
❑ Chapter 7 introduces modules. Modules are a scope whose functions, classes, and data can func-
tion independently of other code, so they can be used separately from any other code in your
program. Modules are the building blocks of Python, as Python’s behavior is extended beyond
the base language by modules that add features. Chapter 7 also introduces Packages, which pro-
vide a structure by associating the files on disk to a deepening scope, using the same form as
that of modules.
❑ Chapter 8 explains files and input/output (I/O). Input/output is the general term for anything
that involves reading data or writing data outside of the program itself. Examples of I/O
include saving and reading files, asking a user a question in a screen, input from a mouse or a
keyboard, and any action that takes place over a network.
❑ Chapter 9 offers examples of many common features of Python that are useful to programmers
and that can be so convenient, but are easily overlooked.
❑ Chapter 10 is an example of a complete Package that combines most of the concepts covered
previously. The module is contrived but provides a complete example of the things that should
be kept in mind when writing modules and packages.

Chapters 11–22 cover more advanced topics. After the language is understood, these examples can be
directly used to build programs that can solve problems in the real world.

❑ Chapter 11 covers dealing with text and regular expressions. Regular expressions are a concept
describing the capability to create rules that can match and change text more flexibly than a lit-
eral letter-by-letter match. Regular expressions provide a syntax to do things such as find all
words that begin with a capital “R” or every file that has a line that begins with a “g” and ends
with an exclamation point.
❑ Chapter 12 delves more deeply into the topic of how to write tests for your modules and pro-
grams so that you can automatically confirm that your program continues to work as you make
changes to it, and so that your clients and users can confirm it works as well.
❑ Chapter 13 introduces programming with a graphical user interface in Python, using GTK+, a
toolkit that is available on Linux, Windows, and MacOS X. A graphical user interface, or GUI, is
any environment that provides windows, buttons, slide-bars and other features that are com-
monly available on modern computers and through which users expect programs to communi-
cate, with the mouse, keyboard, and so on.

xxxiv
Introduction
❑ Chapter 14 shows how to use a database for storing data. The database support available
through Python modules is very powerful, and these modules are available for multiple rela-
tional databases, such as MySQL, Oracle, DB2, and Postgresql.
❑ Chapter 15 focuses on XML, HTML, XSL, and related technologies. XML is a foundational tech-
nology that offers a structured way to access and manipulate text and data. HTML is very simi-
lar to XML, except that it is much simpler and less flexible, and it presents almost all data on the
web one way or the other. XSL is a way to define, in XML, how to transform text, almost like a
language of its own for dealing with documents. Python’s modules to handle these types of
documents very powerful and widely used.
❑ Chapter 16 covers simple networks and programming and e-mail. Most serious programs
require the capability to communicate over the network using network modules. In addition,
e-mail is an extremely common way of using the pervasive network infrastructure provided by
the Internet to send messages to people. Many small and large applications will have some level
of e-mail integration, and Python has the facilities to use e-mail.
❑ Chapter 17 shows how to extend Python for intermediate programmers who have libraries that
they have used or have written in other languages, such as C.
❑ Chapter 18 offers advice, almost a case study, on how to assess the issues involved with packag-
ing shareware or commercial software that has been written in Python.
❑ Chapter 19 covers numerical programming techniques that would often be used in scientific or
other disciplines where advanced math is used.
❑ Chapter 20 provides information for the more advanced user who needs to solve enterprise-
class problems such as workflow and document management.
❑ Chapter 21 covers web applications and APIs that enable applications to access the rich features
available via the Internet from sites such as Google and Yahoo!.
❑ Chapter 22 explores Jython, a version of the Python language that is written in pure Java, and
which enables you to use the Python language while also giving you access to all of the mod-
ules and extensions available to the Java community.

Appendixes
❑ Appendix A provides answers to the exercise questions at the end of each chapter in the book.
❑ Appendix B provides the web sites from which software can be downloaded, and describes the
steps required to install the required software.
❑ Appendix C provides references to more information for people who want to find out more
about Python or the examples in specific chapters.
❑ The Glossary provides definitions of terms that are used in the book.

What You Need to Use This Book


There are some minimal requirements to use the material in this book. The following are recommenda-
tions, as Python itself runs on many different platforms. However, the first chapters assume that you

xxxv
Introduction
have access to a GUI such as is available in Windows, Mac OS X, or the X Window system on Unix and
Linux. Naturally, some chapters, such as the GUI chapter, require the GUI as well, and chapters involv-
ing networking will make much more sense if a network connection is in place.

Following are the suggested minimum requirements:

❑ A PC running Linux, a BSD Unix, or Windows running at 500MHz or faster, or a G3 or later


Macintosh running Mac OS X version 10.2 or later
❑ 256MB of memory (at a minimum)
❑ A graphical user interface — whichever is native to the platform you are on
❑ Administrative access to the computer you are on so that you may install required software
❑ Network access to a TCP/IP network such as the Internet or a campus network
❑ Internet access to download required software
❑ For the enterprise software chapter, an LDAP server needs to be available for testing

Conventions
To help you get the most from the text and keep track of what’s happening, we’ve used a number of con-
ventions throughout the book.

Try It Out
The Try It Out is an exercise you should work through, following the text in the book.

1. They usually consist of a set of steps.


2. Each step has a number.
3. Follow the steps through with your copy of the database.

How It Works
After each Try It Out, the code you’ve typed will be explained in detail.

Boxes like this one hold important, not-to-be forgotten information that is directly
relevant to the surrounding text.

Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.

As for styles in the text:

❑ We highlight new terms and important words when we introduce them.


❑ We show keyboard strokes like this: Ctrl+A.

xxxvi
Introduction
❑ We show file names, URLs, and code within the text like so: persistence.properties.
❑ We present code in two different ways:
In code examples we highlight new and important code with a gray background.

The gray highlighting is not used for code that’s less important in the present
context, or has been shown before.

On the Web Site


As you work through the examples in this book, you may choose to either type in all the code manually
or use the source code files that accompany the book. All the source code used in this book is available
for download at www.wrox.com. Once at the site, simply locate the book’s title by using either the Search
box or one of the topic lists and click the Download Code link. You can then choose what you want to
download from a list of files zipped by chapter.

Because many books have similar titles, you may find it easiest to search by ISBN; for this book the
ISBN is 0-7645-9654-3 (changing to 978-0-7645-9654-4 as the new industry wide 13-digit ISBN
numbering system is phased in by January 2007).

After you download the code, just decompress it with your favorite compression tool. Mac OS X 10.3
and later supports uncompressing zip files directly in the Finder. Alternatively, you can go to the main
Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code avail-
able for this book and all other Wrox books.

Besides source code, you will find some additional resource material on the wrox.com site. When you get
to the download page, as described in the preceding text, look for a file called Additional Resources.zip. In
this file are two documents: Developer Resources and Developer Tools Roadmap. Take a look at these files
when you have a chance. You might find that they offer some valuable information to help you during the
development process.

Errata
We make every effort to ensure that there are no errors in the text or in the code. However, no one is per-
fect, and mistakes do occur. If you find an error in one of our books, such as a spelling mistake or faulty
piece of code, we would be very grateful for your feedback. By sending in errata, you may save another
reader hours of frustration; at the same time, you are helping us provide higher quality information.

To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or
one of the topic lists. When the information page for the book appears, click the Errata link in the
middle of the page. On this page, you can view all errata that has been submitted for this book and
posted by Wrox editors. A complete book list, including links to each book’s errata, is also available at
www.wrox.com/misc-pages/booklist.shtml.

xxxvii
Exploring the Variety of Random
Documents with Different Content
L’Espagnol vantard dit : « — Déjà plusieurs fois, j’ai tenu Roland
tellement serré, que j’aurais pu facilement lui enlever toutes les
armes qu’il avait sur le dos, et non pas seulement son casque. Si je
ne l’ai pas fait, c’est qu’alors je n’avais pas formé le dessein que j’ai
depuis conçu ; maintenant je l’ai résolu, et j’espère pouvoir
l’accomplir sans peine. — »
Roland ne put se contenir plus longtemps ; il cria : « — Menteur,
brute de païen, en quel pays, à quel moment m’as-tu tenu en ton
pouvoir, les armes à la main ? Ce paladin que tu vas te vantant
d’avoir vaincu, c’est moi. Tu pensais qu’il était loin. Or, voyons si tu
pourras m’enlever le casque, ou si je suis bon pour t’enlever à toi-
même tes autres armes ?
« Je ne veux pas conserver sur toi le moindre avantage. — »
Ainsi disant, il délace son casque et le suspend à une branche de
hêtre. En même temps, il tire Durandal. Ferragus, sans perdre le
moins du monde courage, tire son épée et se met en position, de
manière à pouvoir avec elle et avec son écu levé, couvrir sa tête
nue.
Les deux guerriers commencèrent par faire décrire un cercle à
leurs chevaux, tentant avec le fer le défaut de leurs cuirasses. Il n’y
avait pas dans le monde entier un autre couple qu’on eût pu
comparer à celui-là. Égaux en force et en vaillance, ils ne pouvaient
se blesser ni l’un ni l’autre.
Car vous avez déjà entendu dire, mon seigneur, que Ferragus
était invulnérable sur tout le corps, excepté à l’endroit où l’enfant
prend sa première nourriture, alors qu’il est encore dans le ventre de
sa mère. Jusqu’au jour où la pierre sombre du tombeau lui recouvrit
la face, il porta sur cette partie, où il était accessible, sept plaques
d’acier de la meilleure trempe.
Le prince d’Anglante était également invulnérable sur tout le
corps, hors une partie. Il pouvait être blessé sous la plante des
pieds ; mais il la garantissait avec beaucoup de soin et d’art. Le reste
de son corps était plus dur que le diamant, si la renommée nous a
rapporté la vérité. L’un et l’autre, à la poursuite de leurs entreprises,
allaient tout armés, plutôt comme ornement que par besoin.
La bataille devient cruelle, âpre, terrible à voir et pleine
d’épouvante. Ferragus, soit qu’il frappe de la pointe ou de la taille,
ne porte pas une botte qui ne tombe en plein. Chaque coup de
Roland ouvre, rompt ou brise une plaque ou une maille. Angélique,
invisible, assiste seule à un pareil spectacle.
Pendant ce temps, en effet, le roi de Circassie, pensant
qu’Angélique courait non loin en avant, et voyant Ferragus et Roland
aux prises, avait pris le chemin par lequel il croyait que la donzelle
s’était échappée quand elle avait disparu à leurs yeux. C’est ainsi
que la fille de Galafron fut seule témoin de cette bataille.
Après qu’elle l’eut contemplée quelque temps, saisie d’horreur et
d’épouvante, le résultat lui en parut aussi dangereux pour elle d’un
côté comme de l’autre. Une nouvelle pensée lui vient alors à l’esprit ;
elle se décide à enlever le casque pour voir ce que feront les deux
guerriers quand ils s’apercevront qu’il a été enlevé ; elle a toutefois
la pensée de ne pas le garder longtemps.
Elle a bien l’intention de le rendre au comte, mais elle veut
auparavant s’en amuser un peu. Elle détache le casque, puis elle
s’éloigne sans rien leur dire. Elle était déjà loin, avant que l’un d’eux
se fût aperçu du larcin, tellement l’un et l’autre étaient embrasés de
colère.
Mais Ferragus, ayant le premier levé les yeux, s’écarte de
Roland et lui dit : « — Vois, le chevalier qui était avec nous nous a
traités comme des dupes et des sots ! Quel prix le vainqueur
retirera-t-il de sa victoire, puisque celui-ci nous a volé le beau
casque ? — » Roland s’arrête et jette les yeux sur la branche
d’arbre ; il n’y voit plus le casque, et il est tout enflammé de colère.
Comme Ferragus, il conclut que c’était le chevalier qui était
auparavant avec eux qui l’avait emporté. Tournant la bride, il fait
sentir les éperons à Bride-d’Or. Ferragus, le voyant s’éloigner du
champ de bataille, le suivit. Ils arrivèrent bientôt à un endroit où
apparaissaient sur l’herbe les traces nouvelles du Circassien et de la
donzelle.
Le comte prit sa route à gauche, vers une vallée où le Circassien
s’était dirigé lui-même. Quant à Ferragus, il se tint plus près de la
montagne, là où était le sentier qu’Angélique avait suivi. En ce
moment, Angélique était arrivée près d’une fontaine, dans un site
ombreux et agréable, invitant chaque passant à s’arrêter sous ses
ombres fraîches et à ne point la quitter sans y avoir bu.
Angélique s’arrête près des eaux claires, ne pensant pas que
personne survienne. Grâce à l’anneau magique qui la cache, elle ne
craint pas qu’aucun mauvais cas puisse lui arriver. Aussitôt
descendue sur l’herbe épaisse de la rive, elle suspend le casque à
une branche, puis elle cherche l’endroit le plus frais pour y lier sa
jument et la faire paître.
Le chevalier d’Espagne qui avait suivi ses traces arrive à la
fontaine. Angélique ne l’a pas plus tôt vu, qu’elle se rend invisible et
remonte sur sa haquenée. Elle ne peut reprendre le casque qui était
tombé sur l’herbe et avait roulé loin d’elle. Aussitôt que le païen eut
aperçu Angélique, il courut à elle plein de joie.
Mais elle disparut, comme j’ai dit, avant qu’il eût pu la saisir, ainsi
que disparaissent au réveil les fantômes vus en songe. Il s’en va, la
cherchant à travers les arbres, et ses yeux impuissants ne peuvent
plus la voir. Blasphémant Mahomet, Trivigant et tous les chefs de sa
religion, Ferragus s’en revient à la fin vers la fontaine où, dans
l’herbe, gisait le casque du comte.
Il le reconnut, dès qu’il l’eut vu, à l’inscription gravée sur la visière
et qui disait où Roland l’avait acquis, comment et quand, et à qui il
l’avait enlevé. Le païen s’en arma la tête et le col, son chagrin ne
l’empêchant point de le prendre, je veux dire le chagrin qu’il
éprouvait d’avoir vu disparaître sa dame, comme disparaissent les
esprits nocturnes.
Après qu’il a lacé sur sa tête le casque redouté, il pense que,
pour qu’il soit pleinement satisfait, il ne lui reste plus qu’à retrouver
Angélique qui apparaît et disparaît à ses yeux comme un éclair. Il la
chercha par toute la forêt, et quand il eut perdu l’espoir de retrouver
ses traces, il regagna le camp espagnol vers Paris,
Adoucissant la douleur cuisante qu’il éprouvait de n’avoir pu
assouvir son grand désir, par le plaisir de posséder le casque qui
avait appartenu à Roland, ainsi qu’il en avait fait le serment. Le
comte en fut par la suite instruit, et il chercha longtemps Ferragus,
jusqu’au jour où il lui enleva le casque de la tête, après lui avoir
arraché la vie entre deux ponts.
Angélique, invisible et seule, poursuit son chemin, le visage
troublé. Elle regrette qu’une trop grande précipitation lui ait fait
laisser le casque près de la fontaine : « — J’ai fait une chose qu’il
ne m’appartenait pas de faire — se disait-elle à elle-même — en
enlevant au comte son casque. C’est là la première récompense, et
elle est assez étrange, de tant de services que je lui dois !
« C’est dans une bonne intention, Dieu le sait, que j’ai enlevé le
casque, bien que l’effet produit ait été tout autre de ce que
j’espérais. Ma seule pensée fut de mettre fin au combat, et non pas
de donner l’occasion à cette brute d’Espagnol de satisfaire
aujourd’hui son désir. — » Ainsi elle allait, s’accusant elle-même
d’avoir privé Roland de son casque.
Mécontente et de mauvaise humeur, elle prit le chemin qui lui
parut le meilleur pour aller vers l’Orient. La plupart du temps, elle
marchait invisible ; d’autrefois elle se montrait, selon qu’il lui semblait
opportun, et selon les gens qu’elle rencontrait. Après avoir vu de
nombreux pays, elle arriva à un bois où elle trouva un jouvenceau
blessé au beau milieu de la poitrine, et gisant entre deux de ses
compagnons morts.
Mais je n’en dirai pas davantage pour le moment sur Angélique,
car j’ai beaucoup de choses à vous raconter avant de revenir à elle.
Je ne consacrerai pas non plus, du moins de longtemps, d’autres
vers à Ferragus et à Sacripant. Je suis forcé de les laisser pour le
prince d’Anglante, dont je dois m’occuper avant tous les autres. Je
dois dire les fatigues et les angoisses éprouvées par lui à la
poursuite du grand désir qu’il ne parvint jamais à satisfaire.
A la première cité qu’il trouve sur son chemin, comme il a grand
soin de voyager incognito, il met sur sa tête un casque nouveau,
sans regarder si la trempe en est faible ou forte. Qu’elle soit ce
qu’elle voudra, peu lui importe, puisqu’il est rassuré par
l’enchantement qui le rend invulnérable. Ainsi couvert, il poursuit sa
recherche ; le jour, la nuit, la pluie, le soleil ne peuvent l’arrêter.
A l’heure où Phébus fait sortir de la mer ses chevaux au poil
humide, où l’Aurore s’en vient parsemer tout le ciel de fleurs jaunes
et vermeilles, où les étoiles abandonnant leurs chœurs nocturnes
ont déjà disparu sous un voile, Roland, passant un jour près de
Paris, donna une preuve éclatante de sa valeur.
Il se rencontra avec deux escadrons. Le premier était conduit par
Manilard, Sarrasin aux cheveux blancs, roi de Noricie, jadis fier et
vaillant, et maintenant meilleur pour le conseil que pour le combat.
L’autre suivait l’étendard du roi de Trémisène [64] , tenu pour un
chevalier accompli parmi les Africains. Ceux qui le connaissaient
l’appelaient Alzird.
Ces gens, avec le reste de l’armée païenne, avaient séjourné
pendant l’hiver, les uns plus près, les autres plus loin de Paris, logés
tous dans les villas ou dans les châteaux environnants. Le roi
Agramant, après avoir perdu de longs jours à essayer de prendre
Paris, résolut de tenter un assaut final, puisqu’il ne pouvait pas s’en
emparer autrement.
Pour cette entreprise, il disposait de troupes innombrables ; outre
celles qui étaient venues avec lui et celles qui, d’Espagne, avaient
suivi la royale bannière de Marsile, il avait à sa solde beaucoup de
gens de France, car de Paris jusqu’au royaume d’Arles, y compris
une grande partie de la Gascogne — quelques forteresses
exceptées — tout lui était soumis.
A peine les ruisseaux tremblants eurent-ils commencé à fondre la
glace sous leurs eaux tièdes, à peine les prés se furent-ils revêtus
d’herbes nouvelles et les arbres de feuillage tendre, que le roi
Agramant rassembla tous ceux qui suivaient sa fortune, pour réunir
autour de lui son immense armée et donner à ses affaires une
meilleure tournure.
A cet effet, le roi de Trémisène, ainsi que celui de Noricie, s’en
allaient rejoindre en temps voulu le lieu indiqué pour passer en revue
chaque troupe, et voir si elles étaient en bon ou mauvais état.
Roland vint à les rencontrer par hasard, comme je vous ai dit,
marchant tous les deux de compagnie. Quant à lui, il cherchait
toujours, selon qu’il en avait pris l’habitude, celle qui le tenait sous
les chaînes de l’amour.
Dès qu’Alzird vit s’approcher le comte qui n’avait pas son pareil
au monde comme valeur, il lui parut à sa noble prestance, à son
front superbe, l’égal du dieu des armes. Il resta stupéfait devant
cette physionomie ouverte, ce fier regard, ce visage farouche. Il
pensa qu’il avait affaire à un guerrier de haute vaillance, mais il eut
trop de désir de l’éprouver.
Alzird était jeune et présomptueux, estimé pour sa force et son
grand cœur. Il poussa son cheval en avant pour se mesurer avec le
comte. Il eût mieux fait de se tenir avec sa troupe, car au premier
choc le prince d’Anglante le jette à terre après lui avoir traversé le
cœur. Le destrier, ne sentant plus le frein, s’enfuit plein de terreur.
Un cri subit, effroyable, s’élève, emplissant l’air de toutes parts, à
la vue du jeune homme tombant et perdant son sang par une large
ouverture. La troupe frémissante s’en vient au comte en désordre et
le presse de la taille et de la pointe. C’est comme une tempête de
dards empennés qui s’abat sur la fleur des chevaliers vaillants.
La rumeur est pareille à celle produite par une troupe de
sangliers qu’on voit courir sur les coteaux ou à travers les champs,
lorsque le loup sorti de sa caverne obscure, ou l’ours descendu de la
montagne, en ont pris un jeune. Toute la bande se lamente avec des
grognements effroyables. Ainsi la foule des infidèles s’était précipitée
vers le comte en criant : « Sus ! sus ! »
En un instant la cuirasse reçoit mille coups de lance, de flèche et
d’épée, et l’écu autant. Les uns le frappent dans le dos avec la
masse, les autres le menacent par côté, d’autres par devant. Mais
lui, qui ne donna jamais accès à la peur, ne fait pas plus de cas de
cette tourbe vile et de toutes ces armes, que le loup, dans l’obscurité
de la bergerie, ne se préoccupe du nombre des agneaux.
Il tenait nue à la main cette effroyable épée qui a mis à mort tant
de Sarrasins. Aussi, celui qui voudrait compter le nombre de ceux
qui tombent dans cette foule entreprendrait chose longue et difficile.
Bientôt le sang coule le long du chemin rougi et qui peut à peine
contenir tant de morts, car il n’y a ni bouclier ni casque qui puisse
préserver là où l’impitoyable Durandal s’abat,
Non plus que les vêtements rembourrés de coton, ou les tissus
roulés mille fois autour de la tête. Les gémissements et les plaintes
s’élèvent dans les airs, en même temps que volent les bras, les
épaules et les têtes coupés. La Mort cruelle erre sur le champ de
bataille, sous mille formes horribles, et se dit : « — Aux mains de
Roland, Durandal vaut mieux que cent de mes faux. — »
Un coup attend à peine l’autre. Bientôt, ils prennent tous la fuite,
aussi promptement qu’ils étaient d’abord accourus, s’imaginant faire
une bouchée d’un homme seul. Personne n’attend son ami pour
s’ôter de la bagarre et s’éloigner avec lui. L’un fuit à pied, l’autre à
grands renforts d’éperons ; aucun ne s’inquiète de savoir s’il prend la
bonne route.
L’Honneur se tenait près d’eux, avec le miroir qui montre les
taches de l’âme. Aucun d’eux ne s’y regarda, sauf un vieillard, dont
l’âge avait glacé le sang, mais non le courage. Il comprit qu’il lui
valait mieux mourir que se déshonorer en prenant la fuite. Je veux
parler du roi de Noricie. Il met sa lance en arrêt contre le paladin de
France,
Et la rompt sur l’écu du fier comte qui n’en est pas même
ébranlé. Celui-ci, qui avait justement le glaive nu, en porte au roi
Manilard un coup qui devait le traverser. Mais la fortune secourable
voulut que le fer cruel fût mal assuré dans la main de Roland. On ne
peut pas toujours frapper juste. Cependant le coup fait vider l’arçon
Au roi qu’il laisse tout étourdi. Roland ne se retourne point pour le
frapper de nouveau ; il taille, tranche, fend, assomme les autres. Il
semble à tous qu’ils l’ont sur les épaules. De même que par les airs,
où l’espace s’ouvre devant eux, les étourneaux fuient l’audacieux
émerillon, ainsi de toute cette troupe en déroute, les uns tombent,
les autres fuient en se jetant la face contre terre.
L’épée sanglante ne s’arrête point que le champ de bataille ne
soit vide de combattants. Roland hésite alors pour savoir de quel
côté il doit continuer sa route, bien que tout le pays lui soit connu.
Qu’il aille à droite ou à gauche, il ne songe qu’à chercher Angélique,
et craint seulement d’aller où elle n’est pas.
Il poursuivit son chemin, s’informant souvent d’elle, marchant par
les champs et par les bois, comme un homme hors de soi-même. La
nuit venue, il s’écarta de la route, attiré par une lueur, qui, de loin,
s’échappait des fentes d’un rocher situé au pied d’une montagne.
Roland s’approcha du rocher pour voir si Angélique n’était pas
venue s’y reposer.
Comme dans un bois d’humbles genévriers, ou par les chaumes
de la vaste plaine, le chasseur qui poursuit le lièvre peureux,
s’avance d’une marche incertaine à travers les sillons, explorant
chaque buisson, chaque touffe d’herbe pour voir si la bête ne s’y est
pas mise à couvert, ainsi Roland cherchait sa dame avec une
grande patience, partout où l’espoir le poussait.
Le comte, se dirigeant en toute hâte vers ce rayon de lumière,
arriva à un endroit où, au sortir de l’étroit défilé de la montagne, la
forêt s’élargissait, et où se cachait une grotte spacieuse, devant
laquelle croissaient des épines et des jeunes pousses, qui formaient
comme un mur pour dérober ceux qui se trouvaient dans la grotte
aux regards de quiconque aurait voulu leur nuire.
De jour on n’aurait pu la découvrir, mais de nuit, la lumière qui
s’en échappait la faisait apercevoir. Roland s’imaginait bien ce que
c’était. Pourtant il voulait en être plus certain ; après avoir attaché
Bride-d’Or en dehors, il s’approche doucement de la grotte, et
écartant les rameaux touffus, il entre par l’ouverture, sans se faire
annoncer.
Il descend plusieurs degrés dans cette tombe où les gens sont
ensevelis vivants. La grotte, taillée au ciseau, était très spacieuse et
n’était pas tout à fait privée de la lumière du jour, bien que l’entrée
en laissât passer fort peu. Mais il en venait beaucoup d’une fenêtre
qui s’ouvrait dans un trou du rocher à main droite.
Au milieu de la caverne, près d’un feu, était une dame à l’aspect
agréable. Elle avait à peine dépassé quinze ans, comme il parut au
comte au premier abord. Et elle était si belle, qu’elle changeait ce
lieu sauvage en paradis, bien qu’elle eût les yeux baignés de larmes,
signe manifeste d’un cœur dolent.
Près d’elle était une vieille ; elles semblaient en grande
contestation, comme les femmes font souvent entre elles. Mais dès
que le comte fut entré, elles se turent. Roland s’empressa de les
saluer d’un air courtois, ainsi qu’il faut toujours faire avec les dames.
Et elles, se levant aussitôt, lui rendirent gracieusement son salut.
Il est vrai qu’elles s’effrayèrent un peu en entendant à l’improviste
sa voix, et en voyant entrer, armé de toutes pièces, un homme qui
paraissait si terrible. Roland demanda qui pouvait être assez
discourtois, injuste, barbare et atroce, pour tenir enseveli dans cette
grotte un visage si gentil et si digne d’amour.
La jeune fille lui répondit d’une voix faible et entrecoupée de
profonds sanglots. Aux doux accents de sa voix, on eût dit que les
perles et le corail s’échappaient de sa bouche. Les larmes
descendaient sur sa gorge à travers les lis et les roses de ses joues.
Mais qu’il vous plaise, seigneur, d’entendre la suite dans l’autre
chant, car il est désormais temps de finir celui-ci.
CHANT XIII.

Argument. — Isabelle raconte à Roland ses malheurs.


Surviennent les malandrins habitants de la caverne. Roland les tue
tous, puis il part emmenant Isabelle. — Bradamante apprend de
Mélisse que Roger est tombé au pouvoir du vieux magicien. Elle va
pour le délivrer et reste prise dans son propre enchantement. —
Digression élogieuse de Mélisse sur les femmes appartenant à la
maison d’Este.

Ils étaient bien favorisés, les chevaliers qui vivaient à cette époque !
Dans les vallons, dans les cavernes obscures et les bois sauvages,
au milieu des tanières, des serpents, des ours et des lions, ils
trouvaient ce qu’on aurait peine à rencontrer aujourd’hui au sein des
palais superbes, à savoir des dames à la fleur de l’âge et dignes
d’être qualifiées du titre de belles.
Je vous ai raconté plus haut que Roland avait trouvé dans une
grotte une damoiselle, et qu’il lui avait demandé par qui elle y avait
été amenée. Poursuivant le récit de cette aventure, je vous dirai
qu’après s’être plusieurs fois interrompue par ses propres sanglots,
elle mit le comte au courant de ses infortunes, d’une voix douce et
suave, et le plus brièvement qu’elle put.
« — Bien que je sois certaine, chevalier — lui dit-elle — de
porter la peine de ce que je vais te dire — car je pense que cette
vieille s’empressera d’en donner avis à celui qui m’a enfermée ici —
je suis prête à te révéler la vérité, dût ma vie en dépendre. Quel plus
grand service puis-je du reste attendre de lui, sinon qu’il lui prenne
un jour fantaisie de me faire mourir ?
« Je m’appelle Isabelle ; je fus la fille de l’infortuné roi de Galice.
Je dis bien je fus, car je ne suis plus désormais que l’enfant de la
douleur, de l’affliction et de la tristesse. C’est la faute de l’amour, et
je ne sais si c’est de sa perfidie que je dois me plaindre le plus, car
ses doux commencements furent dissimulés sous la tromperie et
sous la fraude.
« Autrefois, je vivais heureuse de mon sort ; noble, jeune, riche,
honnête et belle. Aujourd’hui, je suis humiliée et pauvre ; aujourd’hui
je suis malheureuse. Et s’il est un sort plus terrible encore, il m’est
réservé. Mais je veux que tu connaisses la cause première du
malheur qui me frappe. Bien que tu ne puisses m’être utile en rien, je
pense que par toi ma situation ne peut pas s’aggraver beaucoup.
« Mon père, voici aujourd’hui douze mois, donna à Bayonne des
joutes dont le bruit attira sur nos terres les chevaliers de divers pays,
venus pour y prendre part. Parmi eux tous, soit qu’Amour me le
montrât ainsi, soit que le mérite éclate de lui-même, le seul Zerbin
me parut digne de louanges. Il était fils du grand roi d’Écosse.
« Après l’avoir vu dans la lice accomplir des merveilles de
chevalerie, je fus éprise d’amour pour lui, et je ne m’en aperçus que
lorsque je reconnus que je ne m’appartenais plus moi-même.
Pourtant, bien que cet amour se fût emparé de moi en maître, je
m’applaudissais de ce que le hasard n’avait point mal placé mon
cœur, mais l’avait au contraire donné à l’objet le plus digne qui fût au
monde.
« Zerbin l’emportait sur tous les autres seigneurs en beauté et en
vaillance. Il se montra épris pour moi — et je crois qu’il l’était en effet
— d’un amour non moins ardent que le mien. Nous ne manquâmes
pas de nous exprimer souvent notre commune ardeur, et quand, par
la suite, nous fûmes séparés, nos âmes restèrent toujours unies.
« Car, les grandes fêtes terminées, mon Zerbin retourna en
Écosse. Si tu sais ce que c’est que l’amour, tu peux juger combien je
fus triste, pensant à lui nuit et jour. Et j’étais certaine que sa flamme
ne brûlait pas moins vive dans son cœur. Il n’avait d’autre désir que
de trouver un moyen pour m’avoir près de lui.
« Et comme nos croyances opposées — il était chrétien et moi
musulmane — ne lui permettaient pas de me demander pour femme
à mon père, il se décida à m’enlever secrètement. Sur les confins de
ma riche patrie aux campagnes verdoyantes longeant l’Océan, était
un beau jardin, sur une rive d’où l’on découvrait toutes les collines
environnantes et la mer.
« Ce lieu lui parut propice à l’enlèvement auquel le forçait à
recourir la diversité de nos religions. Il me fit savoir les mesures qu’il
avait prises pour assurer le bonheur de notre vie. Il avait fait cacher
près de Sainte-Marthe une galère montée par des gens armés, sous
la conduite d’Orderic de Biscaye, maître de bataille sur mer et sur
terre.
« Ne pouvant en personne exécuter cette entreprise, parce qu’en
ce moment son vieux père l’avait envoyé porter secours au roi de
France assiégé, il avait envoyé à sa place Orderic, qu’il tenait pour le
plus fidèle et le plus dévoué de ses meilleurs amis. Cela devrait être
en effet, si les bienfaits suffisaient toujours pour se créer des amis.
« Celui-ci était venu sur un navire armé et à l’époque convenue.
Et c’est ainsi qu’arriva le jour tant désiré où je devais me laisser
surprendre dans mon jardin. Orderic, accompagné d’une troupe de
gens habitués aux coups de main maritimes, remonta pendant la
nuit le fleuve voisin de la ville, et vint en silence jusqu’à mon jardin.
« De là, je fus transportée sur la galère, avant qu’on ne s’en fût
aperçu en ville. De mes serviteurs surpris nus et désarmés, les uns
s’enfuirent, les autres furent tués, quelques-uns furent emmenés
captifs avec moi. Ainsi je quittai mon pays, avec une joie que je ne
pourrais te dire, dans l’espoir de jouir bientôt de la présence de mon
Zerbin.
« Nous étions à peine parvenus à la hauteur de la Mangiane,
lorsque nous fûmes assaillis sur notre gauche par un coup de vent
qui obscurcit l’horizon jusqu’alors serein, troubla la mer et souleva
les ondes jusqu’au ciel. Le mistral se mit à souffler en travers de
notre route, augmentant d’heure en heure en violence, à tel point
que nous essayâmes en vain de louvoyer.
« Vainement aussi on largua les voiles, on abaissa le mât sur le
gaillard d’arrière ; nous nous voyions emportés malgré nous sur les
écueils aigus qui sont devant la Rochelle. Si celui qui réside aux
cieux ne nous était pas venu en aide, la tempête farouche nous eût
brisés contre la terre. Le vent furieux nous poussait avec plus de
rapidité qu’une flèche chassée de l’arc.
« Le Biscayen, voyant le péril, usa d’un moyen qui trompe
souvent. Il eut recours à un bateau dans lequel il me fit descendre
avec lui. Deux de nos compagnons y descendirent aussi, et tout le
reste les aurait suivis, si les premiers descendus l’avaient permis.
Mais ils les écartèrent à coups d’épée. Puis ils coupèrent le câble, et
nous prîmes le large.
« Nous fûmes jetés sains et saufs sur le rivage, nous tous qui
étions descendus dans le bateau ; tous les autres périrent avec le
navire et furent la proie des flots. Pour moi, je levai les mains,
rendant grâce à l’éternelle Bonté, à l’Amour infini qui m’avait sauvée
de la fureur de la mer, afin de me permettre de revoir Zerbin.
« J’avais laissé sur le navire mes riches vêtements, mes joyaux
et mes autres choses précieuses, mais l’espoir de revoir Zerbin me
restant, peu m’importait que la mer eût englouti tout ce que je
possédais. Sur le rivage désolé, où nous étions descendus, il n’y a
aucun sentier, aucune habitation ; on y voit seulement une montagne
livrant au vent sa cime ombreuse, et baignant ses pieds dans la mer.
« Ce fut là qu’Amour, ce tyran cruel, toujours si peu loyal à tenir
ses promesses, toujours préoccupé de savoir comment il pourra
déjouer et ruiner nos desseins, changea d’une manière affreuse mon
espoir en douleur, et mon bonheur en malheur irréparable. L’ami à
qui Zerbin s’est fié brûle de désirs et sent sa fidélité se glacer.
« Soit qu’il m’eût déjà désirée quand nous étions en mer, et qu’il
n’eût pas trouvé l’occasion de montrer sa flamme ; soit que ses
désirs eussent pris naissance en me voyant en sa puissance sur un
rivage solitaire, il résolut d’assouvir sans plus de retard son
immonde appétit. Mais auparavant il songea à se débarrasser d’un
des deux marins qui s’étaient échappés avec nous dans le bateau.
« C’était un homme d’Écosse, nommé Almonio, et qui paraissait
tout à fait dévoué à Zerbin, lequel l’avait recommandé à Orderic
comme un guerrier accompli. Orderic lui dit que ce serait chose
blâmable et imprudente que de me faire aller à pied jusqu’à la
Rochelle ; il le pria en conséquence de nous y précéder et de
m’envoyer un cheval.
« Almonio, qui ne concevait aucune crainte, partit immédiatement
pour la ville dont le bois nous cachait la vue, et qui n’était éloignée
que de six milles. Orderic se décide alors à découvrir son dessein à
son autre compagnon, soit qu’il ne sache comment l’éloigner, soit
qu’il ait en lui une entière confiance.
« Celui dont je parle, et qui était resté avec nous, était un nommé
Corèbe, de Bilbao, qui tout enfant avait été élevé dans la même
maison qu’Orderic. Le traître croit pouvoir lui communiquer sa
coupable pensée, espérant qu’il serait plus sensible au plaisir de son
ami qu’à l’honneur.
« Corèbe, en homme gentil et courtois, ne put l’entendre sans
ressentir une grande indignation. Il l’appela traître et s’opposa par
ses paroles et par ses actes à son mauvais dessein. Tous deux,
enflammés de colère, mirent l’épée à la main. En les voyant tirer le
fer, poussée par la peur, je me mis à fuir à travers la forêt sombre.
« Orderic, passé maître dans les armes, prit en quelques coups
un tel avantage, qu’il renversa Corèbe à terre et le laissa pour mort.
Il s’élança aussitôt sur mes traces, et je crois qu’Amour lui prêta ses
ailes pour me rejoindre et lui enseigna toutes sortes de prières et de
paroles séduisantes pour m’amener à l’aimer et à lui céder.
« Mais tout fut vain. J’étais décidée à mourir plutôt que de le
satisfaire. Après qu’il eut compris que les prières, les promesses ou
les menaces ne lui servaient à rien, il voulut user de violence. En
vain je le suppliai, en vain je lui parlai de la confiance que Zerbin
avait mise en lui, et que j’avais eue moi-même en me remettant
entre ses mains.
« Voyant que mes prières ne le touchaient pas, que je n’avais à
espérer aucun secours, et qu’il me pressait de plus en plus,
ressemblant dans sa brutale concupiscence à un ours affamé, je me
défendis avec les pieds, avec les mains, avec les ongles, avec les
dents, je lui arrachai le poil du menton et lui déchirai la peau, tout en
poussant des cris qui montaient jusqu’aux étoiles.
« Je ne sais si ce fut l’effet du hasard, ou de mes cris qui
devaient s’entendre à une lieue, ou bien encore la coutume qu’ont
les habitants de ce pays d’accourir sur le rivage quand un navire s’y
brise et s’y perd, mais je vis soudain apparaître au sommet de la
montagne une troupe de gens qui se dirigea vers nous. Dès que le
Biscayen la vit venir, il abandonna son entreprise et prit la fuite.
« Seigneur, cette foule me sauva de ce traître, mais, pour
employer l’image souvent dite en proverbe, elle me fit tomber de la
poêle dans la braise. Il est vrai que ces gens ne se sont pas encore
montrés assez sauvages et cruels envers moi pour m’avoir fait
violence ; mais ce n’est point par vertu, ni par bonne intention ;
« Car s’ils me conservent vierge, comme je suis, c’est qu’ils
espèrent me vendre plus cher. Voici bientôt huit mois accomplis, et
le neuvième va commencer, que mon corps a été enseveli ici tout
vivant. J’ai perdu tout espoir de revoir mon Zerbin, car, d’après ce
que j’ai déjà pu entendre dire par mes ravisseurs, ils ont promis de
me vendre à un marchand qui doit me conduire au soudan d’Orient.
— »
Ainsi parlait la gente damoiselle, et souvent les sanglots et les
soupirs interrompaient sa voix angélique, de façon à émouvoir de
pitié les serpents et les tigres. Pendant qu’elle renouvelait ainsi sa
douleur, ou calmait peut-être ses tourments, une vingtaine
d’hommes armés d’épieux et de haches entrèrent dans la caverne.
Celui qui paraissait le premier entre eux, homme au visage
farouche, n’avait qu’un œil dont s’échappait un regard louche et
sombre. L’autre œil lui avait été crevé d’un coup qui lui avait coupé
le nez et la mâchoire. En voyant le chevalier assis dans la grotte à
côté de la belle jeune fille, il se tourna vers ses compagnons et dit :
« — Voici un nouvel oiseau, auquel je n’ai pas tendu de filet et que
j’y trouve tout pris. — »
Puis il dit au comte : « — Jamais je n’ai vu d’homme plus
complaisant et plus opportun que toi. Je ne sais si tu as deviné ou si
tu as entendu dire à quelqu’un que je désirais beaucoup posséder
de si belles armes, des vêtements bruns aussi agréables. Tu es
vraiment venu à propos pour satisfaire mes besoins. — »
Roland, remis sur pied, sourit d’un air railleur et répondit au
brigand : « — Je te vendrai les armes à un prix qui ne trouve pas
communément de marchand. — » Et tirant du foyer, qui était près
de lui, un tison enflammé et tout fumant, il en frappa le malandrin à
l’endroit où les sourcils touchent au nez.
Le tison atteignit les deux paupières et causa un tel dommage à
celle de gauche, qu’il creva au misérable le seul œil avec lequel il
pouvait voir encore la lumière. Le coup prodigieux ne se contenta
pas de l’aveugler ; il l’envoya rejoindre les esprits que Chiron, avec
ses compagnons, garde dans des marais de poix bouillante.
Il y avait dans la caverne une grande table, épaisse de deux
palmes et de forme carrée. Posée sur un pied grossier et mal poli,
elle servait au voleur et à toute sa bande. Avec la même agilité que
l’on voit l’adroit Espagnol jeter et rattraper son fusil [65] , Roland lance
la table pesante à l’endroit où se tenait groupée toute cette canaille.
Il rompt à l’un la poitrine, à l’autre le ventre, à celui-ci la tête, à
celui-là les jambes, à un autre les bras. Les uns sont tués du coup,
les autres sont horriblement blessés. Les moins grièvement atteints
s’empressent de fuir. Ainsi, parfois, un gros rocher, tombant sur un
tas de couleuvres, qui, après l’hiver, se chauffent et se lissent au
soleil, leur écrase les flancs et les reins, et leur broie la tête.
Divers cas se produisent, et je ne saurais dire combien : une est
tuée, une s’échappe sans queue, une autre ne peut se mouvoir par
devant et sa partie postérieure en vain s’agite et se dénoue. Une
autre, plus favorisée, rampe en sifflant parmi les herbes et s’en va
en serpentant. Le coup de la table fut terrible ; mais il ne faut pas
s’en étonner, puisqu’il fut porté par le valeureux Roland.
Ceux que la table avait peu ou point blessés — et Turpin écrit
qu’ils ne furent que sept — cherchèrent leur salut dans la rapidité de
leurs pieds. Mais le paladin se mit en travers de l’issue, et après les
avoir pris sans qu’ils se fussent défendus, il leur lia étroitement les
mains avec une corde, qu’il trouva dans la demeure sauvage.
Puis il les traîna hors de la caverne dans un endroit où un vieux
sorbier projetait sa grande ombre. Roland, après en avoir façonné
les branches à coups d’épée, y attacha les prisonniers pour servir de
nourriture aux corbeaux. Et il n’eut pas besoin de leur passer une
corde au cou. Pour purger le monde de cette engeance, l’arbre lui-
même lui fournit des crocs auxquels Roland les attacha par le
menton.
A peine la vieille femme amie des malandrins les eut-elle vus
tous morts, qu’elle s’enfuit en pleurant, les mains dans ses cheveux,
à travers les forêts et les labyrinthes des bois. Après avoir suivi des
chemins rudes et mauvais, rendus encore plus difficiles par la terreur
qu’elle éprouvait, elle rencontra un chevalier sur la rive d’un fleuve.
Mais je remets à plus tard à vous raconter qui c’était,
Et je retourne à la jeune fille qui supplie le paladin de ne pas la
laisser seule, et lui demande à le suivre en tous lieux. Roland la
rassure d’un air courtois. Puis, dès que la blanche Aurore, parée de
sa guirlande de roses et de son voile de pourpre, eut repris son
chemin accoutumé, le paladin partit avec Isabelle.
Sans trouver aucune aventure digne d’être contée, ils marchèrent
plusieurs jours ensemble. Enfin ils rencontrèrent sur leur chemin un
chevalier qu’on emmenait prisonnier. Je vous dirai par la suite qui il
était, car, pour le moment, je suis détourné de ma route par
quelqu’un dont il ne vous sera pas moins cher d’entendre parler ;
j’entends la fille d’Aymon, que j’ai laissée tantôt languissante
d’amoureux chagrins.
La belle dame, attendant en vain le retour de Roger, était à
Marseille, où elle harcelait presque chaque jour les bandes païennes
qui parcouraient, en pillant monts et plaines, le Languedoc et la
Provence. Elle s’y conduisait en chef habile et en vaillant guerrier.
Elle attendait là, et l’époque marquée pour le retour de Roger
étant dépassée de beaucoup, elle vivait, ne le voyant pas revenir,
dans la crainte de mille accidents. Un jour qu’elle pleurait seule à
l’écart en songeant à cela, elle vit arriver celle qui avait jadis, au
moyen de l’anneau, guéri le cœur de Roger des enchantements
d’Alcine.
Comme elle la voit après une si longue absence revenir sans son
amant, Bradamante devient pâle comme la mort, et tremble
tellement qu’elle ne peut se tenir debout. Mais la bonne magicienne
vient à elle en souriant, dès qu’elle s’est aperçue de sa crainte, et la
rassure avec l’air joyeux que prend d’habitude celui qui apporte une
bonne nouvelle.
« — Ne crains pas — lui dit-elle — pour Roger, ô jeune fille, car il
vit sain et sauf et t’adore toujours. Mais il est privé de sa liberté que
lui a encore enlevée ton ennemi. Il faut que tu montes en selle, si tu
veux le délivrer, et que tu me suives sur-le-champ. Si tu me suis, je
te fournirai le moyen par lequel tu rendras Roger libre. — »
Elle poursuivit en lui racontant quelle erreur magique avait ourdie
Atlante, et comment, en montrant à Roger le beau visage de sa
maîtresse qui semblait captive d’un farouche géant, il l’avait attiré
dans le château enchanté, où la vision avait ensuite disparu. Elle lui
dit comment, par une semblable tromperie, il retenait dans le même
lieu les dames et les chevaliers qui y venaient.
Tous, en voyant l’enchanteur, croient voir ce que chacun d’eux
désire le plus ; sa dame, son écuyer, son compagnon d’armes, son
ami ; car le désir humain n’est pas un. Tous vont à travers le palais,
cherchant longtemps et sans autre résultat qu’une longue fatigue.
Leur espérance et leur désir de retrouver l’objet de leurs vœux est si
grand, qu’ils ne savent plus s’en aller.
« — Dès que tu seras arrivée — ajouta-t-elle — dans les
environs de cette demeure enchantée, l’enchanteur viendra à ta
rencontre sous l’apparence complète de Roger. Par son art
détestable, il te fera voir ton amant vaincu par quelqu’un de plus fort
que lui, afin de t’engager à lui porter secours et de t’attirer ainsi là
où, avec les autres, il te tiendra en son pouvoir.
« Pour que tu ne te laisses pas prendre aux pièges dans lesquels
sont tombés tous les autres, je t’avertis que ce n’est qu’une fausse
semblance de Roger que tu verras t’appeler à son aide. Ne te
laisses pas tromper, mais, dès qu’il s’avancera vers toi, arrache-lui
son indigne vie. Ne crois pas que par là tu donneras la mort à Roger,
mais bien à celui qui te cause tant d’ennuis.
« Il te semblera dur, je le reconnais, de tuer quelqu’un qui
ressemble à Roger ; mais n’ajoute point foi à tes yeux auxquels
l’enchanteur cachera la vérité. Prends une ferme résolution, avant
que je te conduise dans le bois, afin de n’en pas changer ensuite,
car tu resteras pour toujours séparée de Roger, si, par faiblesse, tu
laisses la vie au magicien. — »
La vaillante jouvencelle, bien décidée à tuer cet artisan de
fraudes, est prompte à revêtir ses armes et à suivre Mélisse, car elle
sait combien elle lui est dévouée. Celle-ci, tantôt à travers les
champs cultivés, tantôt à travers la forêt, la conduit rapidement à
grandes journées, cherchant par ses paroles réconfortantes à lui
alléger l’ennui de la route.
En dehors des beaux raisonnements qu’elle lui tenait, elle lui
rappelait surtout et le plus souvent possible les glorieux princes et
les demi-dieux qui devaient descendre d’elle et de Roger. Comme
Mélisse connaissait tous les secrets des dieux éternels, elle savait
prédire toutes les choses qui devaient arriver dans la suite des
siècles.
« — Ah ! ma prudente conductrice — disait à la magicienne
l’illustre damoiselle — tu m’as fait connaître ma belle descendance
masculine pendant de nombreuses années ; dis-moi, de même, si,
de ma race, il existera quelque dame digne d’être mise au nombre
des femmes belles et vertueuses. — » Et la complaisante
magicienne lui répondit :
« — Je vois sortir de toi les dames pudiques, mères d’empereurs
et de rois puissants ; réparatrices et soutiens solides de familles
illustres et de vastes domaines, et non moins remarquables sous
leur robe, par leurs précieuses qualités, leur piété, leur grand cœur,
leur sagesse, leur souveraine et incomparable continence, que les
chevaliers sous leurs armures.
« Et si j’avais à te parler de chacune de celles qui seront
l’honneur de ta race, ce serait trop long, car je n’en vois aucune que
je dusse passer sous silence. Mais je ferai, entre mille, choix d’un ou
deux couples, afin de pouvoir arriver jusqu’au bout. Que ne m’as-tu
fait cette demande dans la caverne de Merlin ? Je t’aurais fait voir
aussi leurs images.
« De ton illustre souche sortira l’amie des œuvres illustres et des
beaux travaux ; je ne sais pas ce que je dois le plus louer, de la
grâce et de la beauté, ou de la sagesse et de la chasteté de la
libérale et magnanime Isabelle, dont l’éclatante lumière fera nuit et
jour resplendir la ville située sur le Mincio, et à laquelle la mère
d’Ocnus a donné son nom.
« Elle luttera, avec son digne époux, à qui prisera et aimera le
plus la vertu, et à qui aura le plus de courtoisie. Si de l’un on doit
raconter que, sur les bords du Taro et dans le royaume, il fut assez
puissant pour délivrer l’Italie des Français, on dira de sa compagne,
qui resta seule et chaste, qu’elle égala Pénélope, la femme d’Ulysse.
« Je résume en quelques mots, et j’en laisse plus d’un, les
grands et nombreux mérites de cette dame que Merlin me fit
connaître autrefois dans la grotte, le jour où pour aller à lui je me
séparai du vulgaire. Et si je voulais déployer ma voile sur cette
grande mer, je naviguerais plus longtemps que Tiphys. En somme,
je conclus que le ciel la dotera des vertus les plus remarquables.
« Elle aura près d’elle sa sœur Béatrice à laquelle un tel nom
conviendra de tout point, car non seulement elle possédera pendant
sa vie tous les biens qu’il est permis d’avoir ici-bas, mais elle rendra
son mari le plus heureux des princes, de telle sorte que, lorsqu’elle
aura quitté ce monde, il retombera au rang des plus infortunés.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like