From c3139c443967ed9888b6b238128d4820d324083a Mon Sep 17 00:00:00 2001 From: "(no author)" <(no author)@6015fed2-1504-0410-9fe1-9d1591cc4771> Date: Tue, 15 Jan 2002 22:34:58 +0000 Subject: [PATCH] This commit was manufactured by cvs2svn to create tag 'r212'. git-svn-id: http://svn.python.org/projects/python/tags/r212@25096 6015fed2-1504-0410-9fe1-9d1591cc4771 --- Demo/pdist/new | 1 - Demo/scripts/freeze.py | 480 --- Demo/sgi/video/IN.py | 54 - Demo/sgi/video/Makefile | 7 - Demo/sgi/video/Vrecc.py | 281 -- Demo/sgi/video/cam.py | 129 - Demo/sgi/video/camcorder.py | 266 -- Demo/sgi/video/colorsys.py | 106 - Demo/sgi/video/i2v.c | 80 - Demo/sgi/video/makemovie.py | 218 -- Demo/sgi/video/squash.c | 130 - Demo/sgi/video/squash2.c | 72 - Demo/sgi/video/statit.py | 115 - Demo/sgi/video/syncaudio.py | 94 - Demo/sgi/video/tomono.c | 165 - Demo/sgi/video/tv.py | 79 - Demo/sgi/video/v2i.c | 79 - Demo/sgi/video/vcopy.py | 134 - Demo/sgi/video/video.py | 218 -- Demo/sgi/video/vinfo.py | 90 - Demo/sgi/video/vpregs.py | 28 - Demo/sgi/video/vtime.py | 106 - Demo/sockets/ChangeLog | 35 - Demo/tkinter/Tree.py | 23 - Doc/ACKS | 7 + Doc/Makefile | 2 +- Doc/Makefile.deps | 1 + Doc/README | 59 +- Doc/api/api.tex | 669 ++-- Doc/api/refcounts.dat | 2 +- Doc/doc/doc.tex | 46 +- Doc/ext/ext.tex | 3 + Doc/lib/libanydbm.tex | 16 +- Doc/lib/libascii.tex | 2 +- Doc/lib/libasyncore.tex | 2 +- Doc/lib/libbinascii.tex | 2 +- Doc/lib/libcalendar.tex | 2 +- Doc/lib/libcfgparser.tex | 18 + Doc/lib/libcgi.tex | 5 +- Doc/lib/libcgihttp.tex | 6 +- Doc/lib/libcmd.tex | 25 +- Doc/lib/libcookie.tex | 42 +- Doc/lib/libcrypt.tex | 2 +- Doc/lib/libcurses.tex | 155 +- Doc/lib/libdbhash.tex | 2 +- Doc/lib/libdoctest.tex | 11 + Doc/lib/libfileinput.tex | 7 +- Doc/lib/libfpectl.tex | 4 +- Doc/lib/libgetopt.tex | 3 + Doc/lib/liblocale.tex | 16 +- Doc/lib/libmpz.tex | 13 + Doc/lib/libos.tex | 60 +- Doc/lib/libpipes.tex | 2 +- Doc/lib/libpopen2.tex | 7 +- Doc/lib/libpoplib.tex | 19 +- Doc/lib/libposix.tex | 11 +- Doc/lib/libposixpath.tex | 1 + Doc/lib/libprofile.tex | 12 +- Doc/lib/librandom.tex | 6 +- Doc/lib/libre.tex | 21 +- Doc/lib/libresource.tex | 4 +- Doc/lib/librexec.tex | 125 +- Doc/lib/librfc822.tex | 11 +- Doc/lib/libselect.tex | 6 +- Doc/lib/libshlex.tex | 2 +- Doc/lib/libsmtplib.tex | 9 +- Doc/lib/libsocket.tex | 31 +- Doc/lib/libstdtypes.tex | 11 +- Doc/lib/libstring.tex | 9 - Doc/lib/libsys.tex | 2 +- Doc/lib/libsyslog.tex | 2 +- Doc/lib/libtermios.tex | 2 +- Doc/lib/libthreading.tex | 40 +- Doc/lib/libtime.tex | 36 +- Doc/lib/libweakref.tex | 20 +- Doc/lib/libwebbrowser.tex | 6 +- Doc/lib/libzipfile.tex | 11 +- Doc/lib/libzlib.tex | 7 +- Doc/lib/xmldom.tex | 2 +- Doc/libmods.tex | 7 - Doc/libstd.tex | 7 - Doc/mac/libcolorpicker.tex | 2 +- Doc/mac/libmacui.tex | 48 +- Doc/mac/mac.tex | 4 + Doc/mac/toolbox.tex | 10 +- Doc/mac/undoc.tex | 35 +- Doc/mac/using.tex | 4 +- Doc/perl/l2hinit.perl | 6 +- Doc/perl/python.perl | 49 +- Doc/ref/ref.tex | 4 + Doc/ref/ref3.tex | 39 +- Doc/ref/ref4.tex | 2 +- Doc/ref/ref5.tex | 28 +- Doc/ref/ref6.tex | 19 +- Doc/ref/ref7.tex | 4 +- Doc/templates/howto.tex | 7 + Doc/templates/manual.tex | 7 + Doc/templates/module.tex | 13 +- Doc/texinputs/boilerplate.tex | 5 +- Doc/texinputs/copyright.tex | 122 +- LICENSE => Doc/texinputs/license.tex | 212 +- Doc/texinputs/python.sty | 24 +- Doc/tools/mkhowto | 33 +- Doc/tools/mkmodindex | 43 +- Doc/tools/push-docs.sh | 70 +- Doc/tools/update-docs.sh | 19 +- Doc/tut/tut.tex | 64 +- Doc/whatsnew/whatsnew20.tex | 1335 -------- Doc/whatsnew/whatsnew21.tex | 874 ------ Include/config.h | 82 - Include/patchlevel.h | 6 +- Include/pyport.h | 9 + Include/rangeobject.h | 11 + Include/rename1.h | 360 --- LICENSE | 44 +- Lib/CGIHTTPServer.py | 15 +- Lib/ConfigParser.py | 3 +- Lib/SocketServer.py | 21 +- Lib/anydbm.py | 2 +- Lib/asyncore.py | 29 +- Lib/base64.py | 16 +- Lib/builtin.py | 3 - Lib/cgi.py | 34 +- Lib/compiler/pyassem.py | 31 +- Lib/dbhash.py | 2 +- Lib/distutils/__init__.py | 2 +- Lib/distutils/ccompiler.py | 4 +- Lib/distutils/command/build_scripts.py | 2 + Lib/distutils/mwerkscompiler.py | 19 +- Lib/distutils/sysconfig.py | 6 +- Lib/distutils/unixccompiler.py | 18 +- Lib/doctest.py | 8 +- Lib/dumbdbm.py | 5 + Lib/ftplib.py | 24 +- Lib/gopherlib.py | 2 +- Lib/httplib.py | 9 +- Lib/idlelib/AutoExpand.py | 92 - Lib/idlelib/AutoIndent.py | 554 ---- Lib/idlelib/Bindings.py | 67 - Lib/idlelib/CallTipWindow.py | 71 - Lib/idlelib/CallTips.py | 190 -- Lib/idlelib/ChangeLog | 1017 ------- Lib/idlelib/ClassBrowser.py | 224 -- Lib/idlelib/ColorDelegator.py | 234 -- Lib/idlelib/ConfigParser.py | 382 --- Lib/idlelib/Debugger.py | 308 -- Lib/idlelib/Delegator.py | 34 - Lib/idlelib/EditorWindow.py | 749 ----- Lib/idlelib/ExecBinding.py | 198 -- Lib/idlelib/FileList.py | 150 - Lib/idlelib/FormatParagraph.py | 155 - Lib/idlelib/FrameViewer.py | 38 - Lib/idlelib/GrepDialog.py | 135 - Lib/idlelib/IOBinding.py | 254 -- Lib/idlelib/Icons/folder.gif | Bin 120 -> 0 bytes Lib/idlelib/Icons/minusnode.gif | Bin 75 -> 0 bytes Lib/idlelib/Icons/openfolder.gif | Bin 125 -> 0 bytes Lib/idlelib/Icons/plusnode.gif | Bin 79 -> 0 bytes Lib/idlelib/Icons/python.gif | Bin 895 -> 0 bytes Lib/idlelib/Icons/tk.gif | Bin 85 -> 0 bytes Lib/idlelib/IdleConf.py | 113 - Lib/idlelib/IdleHistory.py | 89 - Lib/idlelib/MultiScrolledLists.py | 138 - Lib/idlelib/MultiStatusBar.py | 32 - Lib/idlelib/NEWS.txt | 130 - Lib/idlelib/ObjectBrowser.py | 151 - Lib/idlelib/OldStackViewer.py | 276 -- Lib/idlelib/OutputWindow.py | 279 -- Lib/idlelib/ParenMatch.py | 192 -- Lib/idlelib/PathBrowser.py | 95 - Lib/idlelib/Percolator.py | 85 - Lib/idlelib/PyParse.py | 569 ---- Lib/idlelib/PyShell.py | 860 ------ Lib/idlelib/README.txt | 121 - Lib/idlelib/Remote.py | 101 - Lib/idlelib/ReplaceDialog.py | 172 -- Lib/idlelib/ScriptBinding.py | 169 -- Lib/idlelib/ScrolledList.py | 139 - Lib/idlelib/SearchBinding.py | 97 - Lib/idlelib/SearchDialog.py | 67 - Lib/idlelib/SearchDialogBase.py | 129 - Lib/idlelib/SearchEngine.py | 221 -- Lib/idlelib/Separator.py | 92 - Lib/idlelib/StackViewer.py | 135 - Lib/idlelib/TODO.txt | 205 -- Lib/idlelib/ToolTip.py | 87 - Lib/idlelib/TreeWidget.py | 471 --- Lib/idlelib/UndoDelegator.py | 352 --- Lib/idlelib/WidgetRedirector.py | 92 - Lib/idlelib/WindowList.py | 85 - Lib/idlelib/ZoomHeight.py | 46 - Lib/idlelib/__init__.py | 1 - Lib/idlelib/config-unix.txt | 3 - Lib/idlelib/config-win.txt | 3 - Lib/idlelib/config.txt | 66 - Lib/idlelib/eventparse.py | 93 - Lib/idlelib/extend.txt | 106 - Lib/idlelib/help.txt | 155 - Lib/idlelib/idle.bat | 3 - Lib/idlelib/idle.py | 12 - Lib/idlelib/idle.pyw | 12 - Lib/idlelib/idlever.py | 1 - Lib/idlelib/keydefs.py | 55 - Lib/idlelib/loader.py | 64 - Lib/idlelib/protocol.py | 369 --- Lib/idlelib/pyclbr.py | 336 --- Lib/idlelib/spawn.py | 58 - Lib/idlelib/tabnanny.py | 372 --- Lib/idlelib/testcode.py | 31 - Lib/imaplib.py | 8 +- Lib/macpath.py | 2 +- Lib/macstat.py | 83 - Lib/nntplib.py | 2 +- Lib/persist.py | 297 -- Lib/pipes.py | 8 +- Lib/poplib.py | 2 +- Lib/profile.py | 43 +- Lib/pstats.py | 2 +- Lib/pyclbr.py | 11 +- Lib/rexec.py | 13 +- Lib/rfc822.py | 2 +- Lib/sgmllib.py | 6 +- Lib/site.py | 40 +- Lib/smtpd.py | 4 +- Lib/smtplib.py | 4 +- Lib/sndhdr.py | 2 +- Lib/socket.py | 6 +- Lib/telnetlib.py | 6 +- Lib/test/output/test_mutants | 1 + Lib/test/output/test_profile | 17 + Lib/test/output/test_scope | 2 + Lib/test/output/test_socketserver | 1 + Lib/test/string_tests.py | 6 + Lib/test/test_b1.py | 7 + Lib/test/test_cfgparser.py | 7 + Lib/test/test_mutants.py | 153 + Lib/test/test_profile.py | 85 + Lib/test/test_pty.py | 8 +- Lib/test/test_scope.py | 31 + Lib/test/test_socket.py | 2 +- Lib/test/test_socketserver.py | 162 + Lib/test/test_strop.py | 2 + Lib/test/test_unicode.py | 6 + Lib/threading.py | 5 +- Lib/traceback.py | 27 +- Lib/unittest.py | 9 +- Lib/urllib.py | 6 +- Lib/urllib2.py | 18 +- Lib/uu.py | 2 +- Lib/webbrowser.py | 635 ++-- Lib/zipfile.py | 13 +- Mac/Build/PythonCore.exp | 184 +- Mac/Build/PythonCore.mcp | Bin 153334 -> 152462 bytes Mac/Build/PythonCoreCarbon.exp | 184 +- Mac/Build/PythonInterpreter.mcp | Bin 122174 -> 122174 bytes Mac/Build/PythonStandSmall.mcp | Bin 262235 -> 262235 bytes Mac/Build/PythonStandalone.mcp | Bin 149425 -> 149425 bytes Mac/Build/_dummy_tkinter.mcp | Bin 50225 -> 50203 bytes Mac/Contrib/AECaptureParser/AECaptureParser.py | 6 +- Mac/Contrib/BBPy.lm/BBPy.c | 2 +- Mac/Contrib/BBPy.lm/PythonBBLM.txt | 2 +- Mac/Contrib/BBPy/PythonSlave.py | 2 +- Mac/Contrib/PythonScript/ReadMe.txt | 2 +- Mac/Contrib/osam/OSAm.prj | Bin 49980 -> 80703 bytes Mac/Contrib/osam/ScriptRunner.c | 19 + Mac/Demo/PICTbrowse/ICONbrowse.py | 4 +- Mac/Demo/PICTbrowse/PICTbrowse.py | 4 +- Mac/Demo/PICTbrowse/PICTbrowse2.py | 6 +- Mac/Demo/PICTbrowse/oldPICTbrowse.py | 6 +- Mac/Demo/applescript/Disk_Copy/Special_Events.py | 16 +- Mac/Demo/applescript/Disk_Copy/Standard_Suite.py | 8 +- Mac/Demo/building.html | 40 +- Mac/Demo/calldll/readme | 9 - Mac/Demo/{textedit/ped.py => mlte/mlted.py} | 244 +- Mac/Demo/quicktime/VerySimplePlayer.py | 2 +- Mac/Demo/textedit/ped.py | 11 +- Mac/Demo/waste/htmled.py | 7 +- Mac/Demo/waste/swed.py | 4 +- Mac/Demo/waste/wed.py | 4 +- Mac/Distributions/(vise)/Python 2.1.vct | Bin 492606 -> 579113 bytes Mac/Distributions/binary.include | 12 +- Mac/Distributions/dev.include | 19 +- Mac/Distributions/readme.txt | 4 + Mac/Distributions/src.exclude | 1 + Mac/Distributions/src.include | 31 +- Mac/IDE scripts/Hack/Toolbox Assistant... | 2 +- Mac/IDE scripts/Widget demos/WidgetTest.py | 4 +- Mac/Include/config.h | 26 +- Mac/Include/getapplbycreator.h | 4 + Mac/Include/macbuildno.h | 2 +- Mac/Include/macglue.h | 29 +- Mac/Include/pymactoolbox.h | 34 +- Mac/Include/pythonresources.h | 3 + Mac/Lib/EasyDialogs.py | 4 +- Mac/Lib/FrameWork.py | 4 + Mac/Lib/MACFS.py | 26 +- Mac/Lib/cfmfile.py | 6 +- Mac/Lib/findertools.py | 8 +- Mac/Lib/lib-scripting/AppleScript_Suite.py | 8 +- .../lib-scripting/CodeWarrior_Standard_Suite.py | 2 +- Mac/Lib/lib-scripting/Finder_Suite.py | 50 +- Mac/Lib/lib-scripting/Metrowerks_Shell_Suite.py | 18 +- Mac/Lib/lib-scripting/Standard_Suite.py | 6 +- Mac/Lib/lib-scripting/Standard_URL_suite.py | 2 +- Mac/Lib/lib-scripting/WWW_Suite.py | 12 +- .../CodeWarrior/CodeWarrior_suite.py | 4 +- .../CodeWarrior/Metrowerks_Shell_Suite.py | 42 +- .../CodeWarrior/Standard_Suite.py | 2 +- .../Finder/Containers_and_folders.py | 4 +- Mac/Lib/lib-scriptpackages/Finder/Earlier_terms.py | 14 +- .../Finder/Files_and_suitcases.py | 6 +- Mac/Lib/lib-scriptpackages/Finder/Finder_Basics.py | 26 +- Mac/Lib/lib-scriptpackages/Finder/Finder_items.py | 4 +- .../lib-scriptpackages/Finder/Obsolete_terms.py | 4 +- .../lib-scriptpackages/Finder/Type_Definitions.py | 2 +- .../lib-scriptpackages/Finder/Window_classes.py | 8 +- .../lib-scriptpackages/Netscape/Mozilla_suite.py | 10 +- Mac/Lib/lib-scriptpackages/Netscape/PowerPlant.py | 4 +- .../lib-scriptpackages/Netscape/Required_suite.py | 2 +- .../lib-scriptpackages/Netscape/Standard_Suite.py | 8 +- .../Netscape/Standard_URL_suite.py | 4 +- Mac/Lib/lib-scriptpackages/Netscape/Text.py | 4 +- .../Netscape/WorldWideWeb_suite.py | 12 +- Mac/Lib/lib-scriptpackages/Netscape/__init__.py | 2 +- .../StdSuites/AppleScript_Suite.py | 14 +- .../lib-scriptpackages/StdSuites/Standard_Suite.py | 12 +- .../lib-scriptpackages/StdSuites/Table_Suite.py | 2 +- Mac/Lib/lib-scriptpackages/StdSuites/Text_Suite.py | 2 +- Mac/Lib/lib-toolbox/AppleEvents.py | 2 +- Mac/Lib/lib-toolbox/Dialogs.py | 2 +- Mac/Lib/lib-toolbox/Icons.py | 32 +- Mac/Lib/lib-toolbox/MacTextEditor.py | 164 + Mac/Lib/macerrors.py | 26 +- Mac/Lib/test/tlist_dialog.rsrc | Bin 513 -> 588 bytes Mac/MPW/buildall | 29 - Mac/Modules/Nav.c | 10 +- Mac/Modules/ae/AEmodule.c | 225 +- Mac/Modules/ae/aescan.py | 1 - Mac/Modules/ae/aesupport.py | 30 +- Mac/Modules/app/Appmodule.c | 223 +- Mac/Modules/app/appsupport.py | 7 +- Mac/Modules/cf/CFmodule.c | 3179 ++++++++++++++++++++ Mac/Modules/cf/cfscan.py | 132 + Mac/Modules/cf/cfsupport.py | 441 +++ Mac/Modules/cm/Cmmodule.c | 182 +- Mac/Modules/cm/cmsupport.py | 32 +- Mac/Modules/ctl/Ctlmodule.c | 553 +--- Mac/Modules/ctl/ctlscan.py | 1 + Mac/Modules/ctl/ctlsupport.py | 63 +- Mac/Modules/dlg/Dlgmodule.c | 283 +- Mac/Modules/dlg/dlgsupport.py | 41 +- Mac/Modules/drag/Dragmodule.c | 185 +- Mac/Modules/drag/dragsupport.py | 29 +- Mac/Modules/evt/Evtmodule.c | 95 +- Mac/Modules/evt/evtsupport.py | 7 +- Mac/Modules/fm/Fmmodule.c | 122 +- Mac/Modules/fm/fmscan.py | 5 + Mac/Modules/fm/fmsupport.py | 14 +- Mac/Modules/gestaltmodule.c | 4 + Mac/Modules/help/Helpmodule.c | 62 +- Mac/Modules/icgluemodule.c | 26 +- Mac/Modules/icn/Icnmodule.c | 251 +- Mac/Modules/icn/icnsupport.py | 7 +- Mac/Modules/list/Listmodule.c | 212 +- Mac/Modules/list/listsupport.py | 24 +- Mac/Modules/macconfig.c | 6 + Mac/Modules/macfsmodule.c | 313 +- Mac/Modules/macmodule.c | 12 +- Mac/Modules/macosmodule.c | 26 +- Mac/Modules/menu/Menumodule.c | 533 +--- Mac/Modules/menu/menusupport.py | 21 +- Mac/Modules/mlte/Mltemodule.c | 1386 +++++++++ Mac/Modules/mlte/mltescan.py | 127 + Mac/Modules/mlte/mltesupport.py | 205 ++ Mac/Modules/qd/Qdmodule.c | 1210 ++------ Mac/Modules/qd/qdsupport.py | 57 +- Mac/Modules/qdoffs/Qdoffsmodule.c | 135 +- Mac/Modules/qdoffs/qdoffssupport.py | 18 +- Mac/Modules/qt/Qtmodule.c | 1711 +++-------- Mac/Modules/qt/qtsupport.py | 59 +- Mac/Modules/res/Resmodule.c | 319 +- Mac/Modules/res/resscan.py | 3 +- Mac/Modules/res/ressupport.py | 31 +- Mac/Modules/scrap/Scrapmodule.c | 7 + Mac/Modules/scrap/scrapsupport.py | 6 +- Mac/Modules/snd/Sndmodule.c | 240 +- Mac/Modules/snd/sndsupport.py | 34 +- Mac/Modules/te/TEmodule.c | 230 +- Mac/Modules/te/tesupport.py | 26 +- Mac/Modules/waste/wastemodule.c | 406 +-- Mac/Modules/waste/wastesupport.py | 2 +- Mac/Modules/win/Winmodule.c | 621 ++-- Mac/Modules/win/winsupport.py | 55 +- Mac/Python/getapplbycreator.c | 4 + Mac/Python/macgetargv.c | 79 +- Mac/Python/macglue.c | 350 ++- Mac/Python/macimport.c | 52 +- Mac/Python/macmain.c | 19 +- Mac/Python/pyGUSISIOUX.cp | 2 + Mac/ReadMe | 36 +- Mac/Relnotes | 172 +- Mac/Resources/dialogs.rsrc | Bin 21172 -> 18570 bytes Mac/Resources/version.r | 2 +- Mac/Tools/IDE/MacPrefs.py | 3 +- Mac/Tools/IDE/ModuleBrowser.py | 12 +- Mac/Tools/IDE/PyBrowser.py | 6 +- Mac/Tools/IDE/PyConsole.py | 17 +- Mac/Tools/IDE/PyDebugger.py | 21 +- Mac/Tools/IDE/PyDocSearch.py | 2 +- Mac/Tools/IDE/PyEdit.py | 64 +- Mac/Tools/IDE/PyFontify.py | 67 +- Mac/Tools/IDE/PythonIDE.py | 4 +- Mac/Tools/IDE/PythonIDE.rsrc | Bin 16544 -> 13828 bytes Mac/Tools/IDE/PythonIDEMain.py | 22 +- Mac/Tools/IDE/Splash.py | 42 +- Mac/Tools/IDE/Wapplication.py | 8 +- Mac/Tools/IDE/Wcontrols.py | 8 - Mac/Tools/IDE/Wtext.py | 11 +- Mac/Tools/IDE/Wtraceback.py | 10 +- Mac/Tools/IDE/Wwindows.py | 2 +- Mac/Unsupported/GUSI1-mods/GUSI.h | 369 --- Mac/Unsupported/GUSI1-mods/GUSI.r | 171 -- Mac/Unsupported/GUSI1-mods/GUSIDispatch.cp | 1437 --------- Mac/Unsupported/GUSI1-mods/GUSINetDB.cp | 582 ---- Mac/Unsupported/GUSI1-mods/GUSISIOUX.cp | 249 -- Mac/Unsupported/GUSI1-mods/GUSI_P.h | 474 --- Mac/Unsupported/mactcp/MACTCPconst.py | 62 - Mac/Unsupported/mactcp/MacTCPerrors.py | 35 - Mac/Unsupported/mactcp/dnrglue.c | 301 -- Mac/Unsupported/mactcp/macdnrmodule.c | 459 --- Mac/Unsupported/mactcp/mactcpmodule.c | 990 ------ Mac/Unsupported/mactcp/mactcpmodules.mu.exp | 2 - Mac/Unsupported/mactcp/mactcpmodules.mu.hqx | 212 -- Mac/Unsupported/mactcp/socket.py | 304 -- Mac/Unsupported/mactcp/tcpglue.c | 477 --- Mac/Unsupported/mactcp/tcpglue.h | 68 - Mac/Unsupported/stdwinmodule.mu.exp | 241 -- Mac/Unsupported/stdwinmodule.mu.hqx | 182 -- Mac/Unsupported/twit/TwitCore.py | 549 ---- Mac/Unsupported/twit/mac_widgets.py | 317 -- Mac/Unsupported/twit/mactwit_app.py | 267 -- Mac/Unsupported/twit/mactwit_browser.py | 429 --- Mac/Unsupported/twit/mactwit_edit.py | 24 - Mac/Unsupported/twit/mactwit_mod.py | 114 - Mac/Unsupported/twit/mactwit_stack.py | 159 - Mac/Unsupported/twit/twit.py | 59 - Mac/Unsupported/twit/twit.rsrc | Bin 46350 -> 0 bytes Mac/Unsupported/twit/twittest.py | 13 - Mac/_checkversion.py | 2 +- Mac/errno_unix.h | 18 - Mac/fopenRF.c | 336 --- Mac/mkapplet.py | 257 -- Mac/mwerks/mwerks_applet_config.h | 1 + Mac/mwerks/mwerks_carbonNOGUSI_config.h | 1 + Mac/mwerks/mwerks_carbon_config.h | 1 + Mac/mwerks/mwerks_carbongusi_config.h | 1 + Mac/mwerks/mwerks_carbonplugin_config.h | 2 + Mac/mwerks/mwerks_config.h | 2 - Mac/mwerks/mwerks_nonshared_config.h | 1 + Mac/mwerks/mwerks_nscarbon_config.h | 1 + Mac/mwerks/mwerks_plugin_config.h | 2 + Mac/mwerks/mwerks_shared_config.h | 2 + Mac/mwerks/mwerks_shcarbon_config.h | 2 + Mac/mwerks/mwerks_shlib_config.h | 3 - Mac/mwerks/mwerks_small_config.h | 1 + Mac/mwerks/mwerks_thrcarbonsm_config.h | 1 + Mac/mwerks/mwerks_threadsmall_config.h | 1 + Mac/mwerks/mwerks_tkplugin_config.h | 1 + Mac/mwerksglue.c | 43 - Mac/scripts/bgenall.py | 38 + Mac/scripts/errors.txt | 26 +- Mac/scripts/fullbuild.py | 4 + Mac/scripts/genpluginprojects.py | 52 +- Mac/tclmods/tclMacNotify.c | 24 +- Misc/ACKS | 1 + Misc/NEWS | 206 +- Modules/_codecsmodule.c | 4 +- Modules/_tkinter.c | 3 +- Modules/binascii.c | 8 +- Modules/gcmodule.c | 24 +- Modules/main.c | 2 +- Modules/mmapmodule.c | 40 +- Modules/parsermodule.c | 2 +- Modules/pcremodule.c | 3 +- Modules/posixmodule.c | 43 +- Modules/readline.c | 4 + Modules/regexmodule.c | 6 +- Modules/selectmodule.c | 73 +- Modules/socketmodule.c | 66 +- Modules/stropmodule.c | 88 +- Modules/structmodule.c | 12 +- Modules/termios.c | 134 +- Modules/timemodule.c | 14 +- Objects/classobject.c | 21 +- Objects/dictobject.c | 129 +- Objects/fileobject.c | 28 +- Objects/frameobject.c | 9 +- Objects/intobject.c | 40 +- Objects/listobject.c | 2 +- Objects/object.c | 59 +- Objects/stringobject.c | 85 +- Objects/tupleobject.c | 15 +- Objects/unicodeobject.c | 19 +- PC/WinMain.c | 2 +- PC/config.h | 7 +- PC/python_nt.rc | 2 +- PCbuild/BUILDno.txt | 8 + PCbuild/installer.bmp | Bin 0 -> 50324 bytes PCbuild/python20.wse | 2784 +++++++++++++---- PCbuild/pythoncore.dsp | 4 +- PCbuild/uninstal.wse | 514 ++++ Python/bltinmodule.c | 28 +- Python/ceval.c | 28 +- Python/compile.c | 160 +- Python/dynload_next.c | 10 +- Python/dynload_shlib.c | 12 +- Python/dynload_win.c | 31 +- Python/errors.c | 2 +- Python/getargs.c | 16 +- Python/getcopyright.c | 2 +- Python/import.c | 52 +- Python/importdl.c | 5 +- Python/pythonmain.c | 211 -- Python/pythonrun.c | 4 + Python/symtable.c | 1 + Python/sysmodule.c | 5 + Python/thread_pthread.h | 13 +- Python/traceback.c | 6 +- README | 65 +- Tools/compiler/compiler/consts.py | 10 +- Tools/compiler/compiler/misc.py | 26 + Tools/compiler/compiler/pyassem.py | 184 +- Tools/compiler/compiler/pycodegen.py | 214 +- Tools/compiler/compiler/symbols.py | 58 +- Tools/compiler/regrtest.py | 41 +- Tools/idle/extend.txt | 26 +- acconfig.h | 9 + config.h.in | 33 +- configure | 797 +++-- configure.in | 83 +- setup.py | 6 +- 541 files changed, 17510 insertions(+), 37826 deletions(-) delete mode 100755 Demo/pdist/new delete mode 100755 Demo/scripts/freeze.py delete mode 100755 Demo/sgi/video/IN.py delete mode 100755 Demo/sgi/video/Makefile delete mode 100755 Demo/sgi/video/Vrecc.py delete mode 100755 Demo/sgi/video/cam.py delete mode 100755 Demo/sgi/video/camcorder.py delete mode 100755 Demo/sgi/video/colorsys.py delete mode 100755 Demo/sgi/video/i2v.c delete mode 100755 Demo/sgi/video/makemovie.py delete mode 100755 Demo/sgi/video/squash.c delete mode 100755 Demo/sgi/video/squash2.c delete mode 100755 Demo/sgi/video/statit.py delete mode 100755 Demo/sgi/video/syncaudio.py delete mode 100755 Demo/sgi/video/tomono.c delete mode 100755 Demo/sgi/video/tv.py delete mode 100755 Demo/sgi/video/v2i.c delete mode 100755 Demo/sgi/video/vcopy.py delete mode 100755 Demo/sgi/video/video.py delete mode 100755 Demo/sgi/video/vinfo.py delete mode 100755 Demo/sgi/video/vpregs.py delete mode 100755 Demo/sgi/video/vtime.py delete mode 100755 Demo/sockets/ChangeLog delete mode 100644 Demo/tkinter/Tree.py delete mode 100755 Doc/libmods.tex delete mode 100755 Doc/libstd.tex rewrite Doc/texinputs/copyright.tex (93%) copy LICENSE => Doc/texinputs/license.tex (54%) delete mode 100644 Doc/whatsnew/whatsnew20.tex delete mode 100644 Doc/whatsnew/whatsnew21.tex delete mode 100755 Include/config.h delete mode 100755 Include/rename1.h delete mode 100755 Lib/builtin.py delete mode 100644 Lib/idlelib/AutoExpand.py delete mode 100644 Lib/idlelib/AutoIndent.py delete mode 100644 Lib/idlelib/Bindings.py delete mode 100644 Lib/idlelib/CallTipWindow.py delete mode 100644 Lib/idlelib/CallTips.py delete mode 100644 Lib/idlelib/ChangeLog delete mode 100644 Lib/idlelib/ClassBrowser.py delete mode 100644 Lib/idlelib/ColorDelegator.py delete mode 100644 Lib/idlelib/ConfigParser.py delete mode 100644 Lib/idlelib/Debugger.py delete mode 100644 Lib/idlelib/Delegator.py delete mode 100644 Lib/idlelib/EditorWindow.py delete mode 100644 Lib/idlelib/ExecBinding.py delete mode 100644 Lib/idlelib/FileList.py delete mode 100644 Lib/idlelib/FormatParagraph.py delete mode 100644 Lib/idlelib/FrameViewer.py delete mode 100644 Lib/idlelib/GrepDialog.py delete mode 100644 Lib/idlelib/IOBinding.py delete mode 100644 Lib/idlelib/Icons/folder.gif delete mode 100644 Lib/idlelib/Icons/minusnode.gif delete mode 100644 Lib/idlelib/Icons/openfolder.gif delete mode 100644 Lib/idlelib/Icons/plusnode.gif delete mode 100644 Lib/idlelib/Icons/python.gif delete mode 100644 Lib/idlelib/Icons/tk.gif delete mode 100644 Lib/idlelib/IdleConf.py delete mode 100644 Lib/idlelib/IdleHistory.py delete mode 100644 Lib/idlelib/MultiScrolledLists.py delete mode 100644 Lib/idlelib/MultiStatusBar.py delete mode 100644 Lib/idlelib/NEWS.txt delete mode 100644 Lib/idlelib/ObjectBrowser.py delete mode 100644 Lib/idlelib/OldStackViewer.py delete mode 100644 Lib/idlelib/OutputWindow.py delete mode 100644 Lib/idlelib/ParenMatch.py delete mode 100644 Lib/idlelib/PathBrowser.py delete mode 100644 Lib/idlelib/Percolator.py delete mode 100644 Lib/idlelib/PyParse.py delete mode 100644 Lib/idlelib/PyShell.py delete mode 100644 Lib/idlelib/README.txt delete mode 100644 Lib/idlelib/Remote.py delete mode 100644 Lib/idlelib/ReplaceDialog.py delete mode 100644 Lib/idlelib/ScriptBinding.py delete mode 100644 Lib/idlelib/ScrolledList.py delete mode 100644 Lib/idlelib/SearchBinding.py delete mode 100644 Lib/idlelib/SearchDialog.py delete mode 100644 Lib/idlelib/SearchDialogBase.py delete mode 100644 Lib/idlelib/SearchEngine.py delete mode 100644 Lib/idlelib/Separator.py delete mode 100644 Lib/idlelib/StackViewer.py delete mode 100644 Lib/idlelib/TODO.txt delete mode 100644 Lib/idlelib/ToolTip.py delete mode 100644 Lib/idlelib/TreeWidget.py delete mode 100644 Lib/idlelib/UndoDelegator.py delete mode 100644 Lib/idlelib/WidgetRedirector.py delete mode 100644 Lib/idlelib/WindowList.py delete mode 100644 Lib/idlelib/ZoomHeight.py delete mode 100644 Lib/idlelib/__init__.py delete mode 100644 Lib/idlelib/config-unix.txt delete mode 100644 Lib/idlelib/config-win.txt delete mode 100644 Lib/idlelib/config.txt delete mode 100644 Lib/idlelib/eventparse.py delete mode 100644 Lib/idlelib/extend.txt delete mode 100644 Lib/idlelib/help.txt delete mode 100755 Lib/idlelib/idle.bat delete mode 100644 Lib/idlelib/idle.py delete mode 100644 Lib/idlelib/idle.pyw delete mode 100644 Lib/idlelib/idlever.py delete mode 100644 Lib/idlelib/keydefs.py delete mode 100644 Lib/idlelib/loader.py delete mode 100644 Lib/idlelib/protocol.py delete mode 100644 Lib/idlelib/pyclbr.py delete mode 100644 Lib/idlelib/spawn.py delete mode 100644 Lib/idlelib/tabnanny.py delete mode 100644 Lib/idlelib/testcode.py delete mode 100755 Lib/macstat.py delete mode 100755 Lib/persist.py create mode 100644 Lib/test/output/test_mutants create mode 100644 Lib/test/output/test_profile create mode 100644 Lib/test/output/test_socketserver create mode 100644 Lib/test/test_mutants.py create mode 100644 Lib/test/test_profile.py create mode 100644 Lib/test/test_socketserver.py rewrite Lib/webbrowser.py (60%) copy Mac/Demo/{textedit/ped.py => mlte/mlted.py} (59%) rewrite Mac/Distributions/(vise)/Python 2.1.vct (92%) create mode 100644 Mac/Lib/lib-toolbox/MacTextEditor.py rewrite Mac/Lib/test/tlist_dialog.rsrc (100%) delete mode 100644 Mac/MPW/buildall create mode 100644 Mac/Modules/cf/CFmodule.c create mode 100644 Mac/Modules/cf/cfscan.py create mode 100644 Mac/Modules/cf/cfsupport.py create mode 100644 Mac/Modules/mlte/Mltemodule.c create mode 100644 Mac/Modules/mlte/mltescan.py create mode 100644 Mac/Modules/mlte/mltesupport.py rewrite Mac/Relnotes (85%) rewrite Mac/Resources/dialogs.rsrc (99%) rewrite Mac/Tools/IDE/PythonIDE.rsrc (99%) delete mode 100644 Mac/Unsupported/GUSI1-mods/GUSI.h delete mode 100644 Mac/Unsupported/GUSI1-mods/GUSI.r delete mode 100644 Mac/Unsupported/GUSI1-mods/GUSIDispatch.cp delete mode 100644 Mac/Unsupported/GUSI1-mods/GUSINetDB.cp delete mode 100644 Mac/Unsupported/GUSI1-mods/GUSISIOUX.cp delete mode 100644 Mac/Unsupported/GUSI1-mods/GUSI_P.h delete mode 100644 Mac/Unsupported/mactcp/MACTCPconst.py delete mode 100644 Mac/Unsupported/mactcp/MacTCPerrors.py delete mode 100644 Mac/Unsupported/mactcp/dnrglue.c delete mode 100644 Mac/Unsupported/mactcp/macdnrmodule.c delete mode 100644 Mac/Unsupported/mactcp/mactcpmodule.c delete mode 100644 Mac/Unsupported/mactcp/mactcpmodules.mu.exp delete mode 100644 Mac/Unsupported/mactcp/mactcpmodules.mu.hqx delete mode 100644 Mac/Unsupported/mactcp/socket.py delete mode 100644 Mac/Unsupported/mactcp/tcpglue.c delete mode 100644 Mac/Unsupported/mactcp/tcpglue.h delete mode 100644 Mac/Unsupported/stdwinmodule.mu.exp delete mode 100644 Mac/Unsupported/stdwinmodule.mu.hqx delete mode 100644 Mac/Unsupported/twit/TwitCore.py delete mode 100644 Mac/Unsupported/twit/mac_widgets.py delete mode 100644 Mac/Unsupported/twit/mactwit_app.py delete mode 100644 Mac/Unsupported/twit/mactwit_browser.py delete mode 100644 Mac/Unsupported/twit/mactwit_edit.py delete mode 100644 Mac/Unsupported/twit/mactwit_mod.py delete mode 100644 Mac/Unsupported/twit/mactwit_stack.py delete mode 100644 Mac/Unsupported/twit/twit.py delete mode 100644 Mac/Unsupported/twit/twit.rsrc delete mode 100644 Mac/Unsupported/twit/twittest.py delete mode 100644 Mac/errno_unix.h delete mode 100644 Mac/fopenRF.c delete mode 100644 Mac/mkapplet.py delete mode 100644 Mac/mwerks/mwerks_config.h delete mode 100644 Mac/mwerks/mwerks_shlib_config.h delete mode 100644 Mac/mwerksglue.c create mode 100644 Mac/scripts/bgenall.py create mode 100644 PCbuild/installer.bmp create mode 100644 PCbuild/uninstal.wse delete mode 100644 Python/pythonmain.c diff --git a/Demo/pdist/new b/Demo/pdist/new deleted file mode 100755 index 9daeafb986..0000000000 --- a/Demo/pdist/new +++ /dev/null @@ -1 +0,0 @@ -test diff --git a/Demo/scripts/freeze.py b/Demo/scripts/freeze.py deleted file mode 100755 index be6d263584..0000000000 --- a/Demo/scripts/freeze.py +++ /dev/null @@ -1,480 +0,0 @@ -#! /usr/local/bin/python - -# Given a Python script, create a binary that runs the script. -# The binary is 100% independent of Python libraries and binaries. -# It will not contain any Python source code -- only "compiled" Python -# (as initialized static variables containing marshalled code objects). -# It even does the right thing for dynamically loaded modules! -# The module search path of the binary is set to the current directory. -# -# Some problems remain: -# - It's highly non-portable, since it knows about paths and libraries -# (there's a customization section though, and it knows how to -# distinguish an SGI from a Sun SPARC system -- adding knowledge -# about more systems is left as an exercise for the reader). -# - You need to have the Python source tree lying around as well as -# the "libpython.a" used to generate the Python binary. -# - For scripts that use many modules it generates absurdly large -# files (frozen.c and config.o as well as the final binary), -# and is consequently rather slow. -# -# Caveats: -# - The search for modules sometimes finds modules that are never -# actually imported since the code importing them is never executed. -# - If an imported module isn't found, you get a warning but the -# process of freezing continues. The binary will fail if it -# actually tries to import one of these modules. -# - This often happens with the module 'mac', which module 'os' tries -# to import (to determine whether it is running on a Macintosh). -# You can ignore the warning about this. -# - If the program dynamically reads or generates Python code and -# executes it, this code may reference built-in or library modules -# that aren't present in the frozen binary, and this will fail. -# - Your program may be using external data files, e.g. compiled -# forms definitions (*.fd). These aren't incorporated. Since -# sys.path in the resulting binary only contains '.', if your -# program searches its data files along sys.path (as the 'flp' -# modules does to find its forms definitions), you may need to -# change the program to extend the search path or instruct its users -# to set the environment variable PYTHONPATH to point to your data -# files. -# -# Usage hints: -# - If you have a bunch of scripts that you want to freeze, instead -# of freezing each of them separately, you might consider writing -# a tiny main script that looks at sys.argv[0] and then imports -# the corresponding module. You can then make links to the -# frozen binary named after the various scripts you support. -# Pass the additional scripts as arguments after the main script. -# A minimal script to do this is the following. -# import sys, posixpath -# exec('import ' + posixpath.basename(sys.argv[0]) + '\n') - - -import os -import sys -import regex -import getopt -import regsub -import string -import marshal - -# Function to join two pathnames with a slash in between -j = os.path.join - -################################## -# START OF CONFIGURATION SECTION # -################################## - -# Attempt to guess machine architecture -if os.path.exists('/usr/lib/libgl_s'): ARCH = 'sgi' -elif os.path.exists('/etc/issue'): ARCH = 'sequent' -else: ARCH = 'sun4' - -# Site parametrizations (change to match your site) -CC = 'cc' # C compiler -TOP = '/ufs/guido/src' # Parent of all source trees -PYTHON = j(TOP, 'python') # Top of the Python source tree -SRC = j(PYTHON, 'src') # Python source directory -BLD = j(PYTHON, 'build.' + ARCH) # Python build directory -#BLD = SRC # Use this if you build in SRC - -LIBINST = '/ufs/guido/src/python/irix4/tmp/lib/python/lib' # installed libraries -INCLINST = '/ufs/guido/src/python/irix4/tmp/include/Py' # installed include files - -# Other packages (change to match your site) -DL = j(TOP, 'dl') # Top of the dl source tree -DL_DLD = j(TOP, 'dl-dld') # The dl-dld source directory -DLD = j(TOP, 'dld-3.2.3') # The dld source directory -FORMS = j(TOP, 'forms') # Top of the FORMS source tree -STDWIN = j(TOP, 'stdwin') # Top of the STDWIN source tree -READLINE = j(TOP, 'readline.' + ARCH) # Top of the GNU Readline source tree -SUN_X11 = '/usr/local/X11R5/lib/libX11.a' - -# File names (usually no need to change) -LIBP = [ # Main Python libraries - j(LIBINST, 'libPython.a'), - j(LIBINST, 'libParser.a'), - j(LIBINST, 'libObjects.a'), - j(LIBINST, 'libModules.a') - ] -CONFIG_IN = j(LIBINST, 'config.c.in') # Configuration source file -FMAIN = j(LIBINST, 'frozenmain.c') # Special main source file - -# Libraries needed when linking. First tuple item is built-in module -# for which it is needed (or '*' for always), rest are ld arguments. -# There is a separate list per architecture. -libdeps_sgi = [ \ - ('stdwin', j(STDWIN, 'Build/' + ARCH + '/x11/lib/lib.a')), \ - ('fl', j(FORMS, 'FORMS/libforms.a'), '-lfm_s'), \ - ('*', j(READLINE, 'libreadline.a'), '-ltermcap'), \ - ('al', '-laudio'), \ - ('sv', '-lsvideo', '-lXext'), \ - ('cd', '-lcdaudio', '-lds'), \ - ('cl', '-lcl'), \ - ('imgfile', '-limage', '-lgutil', '-lm'), \ - ('mpz', '/ufs/guido/src/gmp/libgmp.a'), \ - ('*', '-lsun'), \ - ('*', j(DL, 'libdl.a'), '-lmld'), \ - ('*', '-lmpc'), \ - ('fm', '-lfm_s'), \ - ('gl', '-lgl_s', '-lX11_s'), \ - ('stdwin', '-lX11_s'), \ - ('*', '-lm'), \ - ('*', '-lc_s'), \ - ] -libdeps_sun4 = [ \ - ('*', '-Bstatic'), \ - ('stdwin', j(STDWIN, 'Build/' + ARCH + '/x11/lib/lib.a')), \ - ('*', j(READLINE, 'libreadline.a')), \ - ('*', '-lm'), \ - ('*', j(DL_DLD,'libdl.a'), j(DLD,'libdld.a')), \ - ('*', SUN_X11), \ - ('*', '-ltermcap'), \ - ('*', '-lc'), \ - ] -libdeps_sequent = [ \ - ('*', j(LIBINST, 'libreadline.a'), '-ltermcap'), \ - ('*', '-lsocket'), \ - ('*', '-linet'), \ - ('*', '-lnsl'), \ - ('*', '-lm'), \ - ('*', '-lc'), \ - ] -libdeps = eval('libdeps_' + ARCH) - -################################ -# END OF CONFIGURATION SECTION # -################################ - -# Exception used when scanfile fails -NoSuchFile = 'NoSuchFile' - -# Global options -quiet = 0 # -q -verbose = 0 # -v -noexec = 0 # -n -nowrite = 0 # -N -ofile = 'a.out' # -o file - -# Main program -- argument parsing etc. -def main(): - global quiet, verbose, noexec, nowrite, ofile - try: - opts, args = getopt.getopt(sys.argv[1:], 'nNo:qv') - except getopt.error, msg: - usage(str(msg)) - sys.exit(2) - for o, a in opts: - if o == '-n': noexec = 1 - if o == '-N': nowrite = 1 - if o == '-o': ofile = a - if o == '-q': verbose = 0; quiet = 1 - if o == '-v': verbose = verbose + 1; quiet = 0 - if len(args) < 1: - usage('please pass at least one file argument') - sys.exit(2) - process(args[0], args[1:]) - -# Print usage message to stderr -def usage(*msgs): - sys.stdout = sys.stderr - for msg in msgs: print msg - print 'Usage: freeze [options] scriptfile [modulefile ...]' - print '-n : generate the files but don\'t compile and link' - print '-N : don\'t write frozen.c (do compile unless -n given)' - print '-o file : binary output file (default a.out)' - print '-q : quiet (no messages at all except errors)' - print '-v : verbose (lots of extra messages)' - -# Process the script file -def process(filename, addmodules): - global noexec - # - if not quiet: print 'Computing needed modules ...' - todo = {} - todo['__main__'] = filename - for name in addmodules: - mod = os.path.basename(name) - if mod[-3:] == '.py': mod = mod[:-3] - todo[mod] = name - try: - dict = closure(todo) - except NoSuchFile, filename: - sys.stderr.write('Can\'t open file %s\n' % filename) - sys.exit(1) - # - mods = dict.keys() - mods.sort() - # - if verbose: - print '%-15s %s' % ('Module', 'Filename') - for mod in mods: - print '%-15s %s' % (`mod`, dict[mod]) - # - if not quiet: print 'Looking for dynamically linked modules ...' - dlmodules = [] - objs = [] - libs = [] - for mod in mods: - if dict[mod][-2:] == '.o': - if verbose: print 'Found', mod, dict[mod] - dlmodules.append(mod) - objs.append(dict[mod]) - libsname = dict[mod][:-2] + '.libs' - try: - f = open(libsname, 'r') - except IOError: - f = None - if f: - libtext = f.read() - f.close() - for lib in string.split(libtext): - if lib in libs: libs.remove(lib) - libs.append(lib) - # - if not nowrite: - if not quiet: print 'Writing frozen.c ...' - writefrozen('frozen.c', dict) - else: - if not quiet: print 'NOT writing frozen.c ...' - # -## if not dlmodules: - if 0: - config = CONFIG - if not quiet: print 'Using existing', config, '...' - else: - config = 'tmpconfig.c' - if nowrite: - if not quiet: print 'NOT writing config.c ...' - else: - if not quiet: - print 'Writing config.c with dl modules ...' - f = open(CONFIG_IN, 'r') - g = open(config, 'w') - m1 = regex.compile('-- ADDMODULE MARKER 1 --') - m2 = regex.compile('-- ADDMODULE MARKER 2 --') - builtinmodules = [] - stdmodules = ('sys', '__main__', '__builtin__', - 'marshal') - todomodules = builtinmodules + dlmodules - for mod in dict.keys(): - if dict[mod] == '' and \ - mod not in stdmodules: - builtinmodules.append(mod) - while 1: - line = f.readline() - if not line: break - g.write(line) - if m1.search(line) >= 0: - if verbose: print 'Marker 1 ...' - for mod in todomodules: - g.write('extern void init' + \ - mod + '();\n') - if m2.search(line) >= 0: - if verbose: print 'Marker 2 ...' - for mod in todomodules: - g.write('{"' + mod + \ - '", init' + mod + '},\n') - g.close() - # - if not quiet: - if noexec: print 'Generating compilation commands ...' - else: print 'Starting compilation ...' - defs = ['-DNO_MAIN', '-DUSE_FROZEN', '-DPYTHONPATH=\'"."\''] - # - incs = ['-I.', '-I' + INCLINST] - if dict.has_key('stdwin'): - incs.append('-I' + j(STDWIN, 'H')) - # - srcs = [config, FMAIN] - # - if type(LIBP) == type(''): - libs.append(LIBP) - else: - for lib in LIBP: - libs.append(lib) - for item in libdeps: - m = item[0] - if m == '*' or dict.has_key(m): - for l in item[1:]: - if l in libs: libs.remove(l) - libs.append(l) - # - sts = 0 - # - cmd = CC + ' -c' - cmd = cmd + ' ' + string.join(defs) - cmd = cmd + ' ' + string.join(incs) - cmd = cmd + ' ' + string.join(srcs) - print cmd - # - if not noexec: - sts = os.system(cmd) - if sts: - print 'Exit status', sts, '-- turning on -n' - noexec = 1 - # - for s in srcs: - s = os.path.basename(s) - if s[-2:] == '.c': s = s[:-2] - o = s + '.o' - objs.insert(0, o) - # - cmd = CC - cmd = cmd + ' ' + string.join(objs) - cmd = cmd + ' ' + string.join(libs) - cmd = cmd + ' -o ' + ofile - print cmd - # - if not noexec: - sts = os.system(cmd) - if sts: - print 'Exit status', sts - else: - print 'Done.' - # - if not quiet and not noexec and sts == 0: - print 'Note: consider this:'; print '\tstrip', ofile - # - sys.exit(sts) - - -# Generate code for a given module -def makecode(filename): - if filename[-2:] == '.o': - return None - try: - f = open(filename, 'r') - except IOError: - return None - if verbose: print 'Making code from', filename, '...' - text = f.read() - code = compile(text, filename, 'exec') - f.close() - return marshal.dumps(code) - - -# Write the C source file containing the frozen Python code -def writefrozen(filename, dict): - f = open(filename, 'w') - codelist = [] - for mod in dict.keys(): - codestring = makecode(dict[mod]) - if codestring is not None: - codelist.append((mod, codestring)) - write = sys.stdout.write - save_stdout = sys.stdout - try: - sys.stdout = f - for mod, codestring in codelist: - if verbose: - write('Writing initializer for %s\n'%mod) - print 'static unsigned char M_' + mod + '[' + \ - str(len(codestring)) + '+1] = {' - for i in range(0, len(codestring), 16): - for c in codestring[i:i+16]: - print str(ord(c)) + ',', - print - print '};' - print 'struct frozen {' - print ' char *name;' - print ' unsigned char *code;' - print ' int size;' - print '} frozen_modules[] = {' - for mod, codestring in codelist: - print ' {"' + mod + '",', - print 'M_' + mod + ',', - print str(len(codestring)) + '},' - print ' {0, 0, 0} /* sentinel */' - print '};' - finally: - sys.stdout = save_stdout - f.close() - - -# Determine the names and filenames of the modules imported by the -# script, recursively. This is done by scanning for lines containing -# import statements. (The scanning has only superficial knowledge of -# Python syntax and no knowledge of semantics, so in theory the result -# may be incorrect -- however this is quite unlikely if you don't -# intentionally obscure your Python code.) - -# Compute the closure of scanfile() -- special first file because of script -def closure(todo): - done = {} - while todo: - newtodo = {} - for modname in todo.keys(): - if not done.has_key(modname): - filename = todo[modname] - if filename is None: - filename = findmodule(modname) - done[modname] = filename - if filename in ('', ''): - continue - modules = scanfile(filename) - for m in modules: - if not done.has_key(m): - newtodo[m] = None - todo = newtodo - return done - -# Scan a file looking for import statements -importstr = '\(^\|:\)[ \t]*import[ \t]+\([a-zA-Z0-9_, \t]+\)' -fromstr = '\(^\|:\)[ \t]*from[ \t]+\([a-zA-Z0-9_]+\)[ \t]+import[ \t]+' -isimport = regex.compile(importstr) -isfrom = regex.compile(fromstr) -def scanfile(filename): - allmodules = {} - try: - f = open(filename, 'r') - except IOError, msg: - raise NoSuchFile, filename - while 1: - line = f.readline() - if not line: break # EOF - while line[-2:] == '\\\n': # Continuation line - line = line[:-2] + ' ' - line = line + f.readline() - if isimport.search(line) >= 0: - rawmodules = isimport.group(2) - modules = string.splitfields(rawmodules, ',') - for i in range(len(modules)): - modules[i] = string.strip(modules[i]) - elif isfrom.search(line) >= 0: - modules = [isfrom.group(2)] - else: - continue - for mod in modules: - allmodules[mod] = None - f.close() - return allmodules.keys() - -# Find the file containing a module, given its name; None if not found -builtins = sys.builtin_module_names + ['sys'] -def findmodule(modname): - if modname in builtins: return '' - for dirname in sys.path: - dlfullname = os.path.join(dirname, modname + 'module.o') - try: - f = open(dlfullname, 'r') - except IOError: - f = None - if f: - f.close() - return dlfullname - fullname = os.path.join(dirname, modname + '.py') - try: - f = open(fullname, 'r') - except IOError: - continue - f.close() - return fullname - if not quiet: - sys.stderr.write('Warning: module %s not found\n' % modname) - return '' - - -# Call the main program -main() diff --git a/Demo/sgi/video/IN.py b/Demo/sgi/video/IN.py deleted file mode 100755 index ffc2852596..0000000000 --- a/Demo/sgi/video/IN.py +++ /dev/null @@ -1,54 +0,0 @@ -IPPROTO_IP = 0 -IPPROTO_ICMP = 1 -IPPROTO_IGMP = 2 -IPPROTO_GGP = 3 -IPPROTO_TCP = 6 -IPPROTO_EGP = 8 -IPPROTO_PUP = 12 -IPPROTO_UDP = 17 -IPPROTO_IDP = 22 -IPPROTO_TP = 29 -IPPROTO_XTP = 36 -IPPROTO_EON = 80 -IPPROTO_RAW = 255 -IPPROTO_MAX = 256 -IPPORT_RESERVED = 1024 -IPPORT_USERRESERVED = 5000 -IN_CLASSA_NET = 0xff000000 -IN_CLASSA_NSHIFT = 24 -IN_CLASSA_HOST = 0x00ffffff -IN_CLASSA_MAX = 128 -IN_CLASSB_NET = 0xffff0000 -IN_CLASSB_NSHIFT = 16 -IN_CLASSB_HOST = 0x0000ffff -IN_CLASSB_MAX = 65536 -IN_CLASSC_NET = 0xffffff00 -IN_CLASSC_NSHIFT = 8 -IN_CLASSC_HOST = 0x000000ff -IN_CLASSD_NET = 0xf0000000 -IN_CLASSD_NSHIFT = 28 -IN_CLASSD_HOST = 0x0fffffff -INADDR_ANY = 0x00000000 -INADDR_BROADCAST = 0xffffffff -INADDR_LOOPBACK = 0x7F000001 -INADDR_UNSPEC_GROUP = 0xe0000000 -INADDR_ALLHOSTS_GROUP = 0xe0000001 -INADDR_MAX_LOCAL_GROUP = 0xe00000ff -INADDR_NONE = 0xffffffff -IN_LOOPBACKNET = 127 -IP_OPTIONS = 1 -IP_HDRINCL = 7 -IP_TOS = 8 -IP_TTL = 9 -IP_RECVOPTS = 10 -IP_RECVRETOPTS = 11 -IP_RECVDSTADDR = 12 -IP_RETOPTS = 13 -IP_MULTICAST_IF = 2 -IP_MULTICAST_TTL = 3 -IP_MULTICAST_LOOP = 4 -IP_ADD_MEMBERSHIP = 5 -IP_DROP_MEMBERSHIP = 6 -IP_DEFAULT_MULTICAST_TTL = 1 -IP_DEFAULT_MULTICAST_LOOP = 1 -IP_MAX_MEMBERSHIPS = 20 diff --git a/Demo/sgi/video/Makefile b/Demo/sgi/video/Makefile deleted file mode 100755 index 266ea52587..0000000000 --- a/Demo/sgi/video/Makefile +++ /dev/null @@ -1,7 +0,0 @@ -all: v2i i2v - -v2i: v2i.o - $(CC) v2i.o -limage -o v2i - -i2v: i2v.o - $(CC) i2v.o -limage -o i2v diff --git a/Demo/sgi/video/Vrecc.py b/Demo/sgi/video/Vrecc.py deleted file mode 100755 index 6a539f8192..0000000000 --- a/Demo/sgi/video/Vrecc.py +++ /dev/null @@ -1,281 +0,0 @@ -#! /ufs/guido/bin/sgi/python-405 -#! /ufs/guido/bin/sgi/python - -# Capture a continuous CMIF movie using the Indigo video library and board - - -# Usage: -# -# makemovie [-r rate] [-w width] [moviefile] - - -# Options: -# -# -r rate : capture 1 out of every 'rate' frames (default 1) -# -w width : initial window width (default interactive placement) -# -d : drop fields if needed -# -g bits : greyscale (2, 4 or 8 bits) -# -G : 2-bit greyscale dithered -# -m : monochrome dithered -# -M value : monochrome tresholded with value -# -f : Capture fields (in stead of frames) -# -n number : Capture 'number' fields (default 60) -# -# moviefile : here goes the movie data (default film.video); -# the format is documented in cmif-film.ms - - -# User interface: -# -# Start the application. Resize the window to the desired movie size. -# Press the left mouse button to start recording, release it to end -# recording. You can record as many times as you wish, but each time -# you overwrite the output file(s), so only the last recording is -# kept. -# -# Press ESC or select the window manager Quit or Close window option -# to quit. If you quit before recording anything, the output file(s) -# are not touched. - - -import sys -sys.path.append('/ufs/guido/src/video') -import sv, SV -import VFile -import gl, GL, DEVICE -import al, AL -import time -import posix -import getopt -import string -import imageop -import sgi - -# Main program - -def main(): - format = SV.RGB8_FRAMES - rate = 1 - width = 0 - drop = 0 - mono = 0 - grey = 0 - greybits = 0 - monotreshold = -1 - fields = 0 - number = 60 - - opts, args = getopt.getopt(sys.argv[1:], 'r:w:dg:mM:Gfn:') - for opt, arg in opts: - if opt == '-r': - rate = string.atoi(arg) - if rate < 2: - sys.stderr.write('-r rate must be >= 2\n') - sys.exit(2) - elif opt == '-w': - width = string.atoi(arg) - elif opt == '-d': - drop = 1 - elif opt == '-g': - grey = 1 - greybits = string.atoi(arg) - if not greybits in (2,4,8): - print 'Only 2, 4 or 8 bit greyscale supported' - elif opt == '-G': - grey = 1 - greybits = -2 - elif opt == '-m': - mono = 1 - elif opt == '-M': - mono = 1 - monotreshold = string.atoi(arg) - elif opt == '-f': - fields = 1 - elif opt == '-n': - number = string.atoi(arg) - - if args[2:]: - sys.stderr.write('usage: Vrec [options] [file]\n') - sys.exit(2) - - if args: - filename = args[0] - else: - filename = 'film.video' - - v = sv.OpenVideo() - # Determine maximum window size based on signal standard - param = [SV.BROADCAST, 0] - v.GetParam(param) - if param[1] == SV.PAL: - x = SV.PAL_XMAX - y = SV.PAL_YMAX - elif param[1] == SV.NTSC: - x = SV.NTSC_XMAX - y = SV.NTSC_YMAX - else: - print 'Unknown video standard', param[1] - sys.exit(1) - - gl.foreground() - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - if width: - gl.prefsize(width, width*3/4) - win = gl.winopen(filename) - if width: - gl.maxsize(x, y) - gl.keepaspect(x, y) - gl.stepunit(8, 6) - gl.winconstraints() - x, y = gl.getsize() - print x, 'x', y - - v.SetSize(x, y) - - if drop: - param = [SV.FIELDDROP, 1, SV.GENLOCK, SV.GENLOCK_OFF] - else: - param = [SV.FIELDDROP, 0, SV.GENLOCK, SV.GENLOCK_ON] - if mono or grey: - param = param+[SV.COLOR, SV.MONO, SV.INPUT_BYPASS, 1] - else: - param = param+[SV.COLOR, SV.DEFAULT_COLOR, SV.INPUT_BYPASS, 0] - v.SetParam(param) - - v.BindGLWindow(win, SV.IN_REPLACE) - - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - - print 'Press left mouse to start recording' - - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE: - if val == 1: - info = format, x, y, number, rate - record(v, info, filename, mono, grey, \ - greybits, monotreshold, fields) - elif dev == DEVICE.REDRAW: - # Window resize (or move) - x, y = gl.getsize() - print x, 'x', y - v.SetSize(x, y) - v.BindGLWindow(win, SV.IN_REPLACE) - elif dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - # Quit - v.CloseVideo() - gl.winclose(win) - break - - -# Record until the mouse is released (or any other GL event) -# XXX audio not yet supported - -def record(v, info, filename, mono, grey, greybits, monotreshold, fields): - import thread - format, x, y, number, rate = info - fps = 59.64 # Fields per second - # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) - tpf = 1000.0 / fps # Time per field in msec - # - # Go grab - # - gl.wintitle('(rec) ' + filename) - try: - ninfo, data, bitvec = v.CaptureBurst(info) - except sv.error, arg: - print 'CaptureBurst failed:', arg - print 'info:', info - gl.wintitle(filename) - return - gl.wintitle('(save) '+ filename) - # - # Check results - # - if info <> ninfo: - print 'Sorry, format changed.' - print 'Wanted:',info - print 'Got :',ninfo - gl.wintitle(filename) - return - # print bitvec - if x*y*number <> len(data): - print 'Funny data length: wanted',x,'*',y,'*', number,'=',\ - x*y*number,'got',len(data) - gl.wintitle(filename) - return - # - # Save - # - if filename: - # - # Construct header and write it - # - vout = VFile.VoutFile().init(filename) - if mono: - vout.format = 'mono' - elif grey and greybits == 8: - vout.format = 'grey' - elif grey: - vout.format = 'grey'+`abs(greybits)` - else: - vout.format = 'rgb8' - vout.width = x - vout.height = y - if fields: - vout.packfactor = (1,-2) - else: - print 'Sorry, can only save fields at the moment' - gl.wintitle(filename) - return - vout.writeheader() - # - # Compute convertor, if needed - # - convertor = None - if grey: - if greybits == 2: - convertor = imageop.grey2grey2 - elif greybits == 4: - convertor = imageop.grey2grey4 - elif greybits == -2: - convertor = imageop.dither2grey2 - fieldsize = x*y/2 - nskipped = 0 - realframeno = 0 - tpf = 1000 / 50.0 #XXXX - for frameno in range(0, number*2): - if frameno <> 0 and \ - bitvec[frameno] == bitvec[frameno-1]: - nskipped = nskipped + 1 - continue - # - # Save field. - # XXXX Works only for fields and top-to-bottom - # - start = frameno*fieldsize - field = data[start:start+fieldsize] - if convertor: - field = convertor(field, x, y) - elif mono and monotreshold >= 0: - field = imageop.grey2mono(field, x, y, \ - 1, monotreshold) - elif mono: - field = imageop.dither2mono(field, x, y) - vout.writeframe(int(realframeno*tpf), field, None) - print 'Skipped',nskipped,'duplicate frames' - vout.close() - - gl.wintitle('(done) ' + filename) - -# Don't forget to call the main program - -try: - main() -except KeyboardInterrupt: - print '[Interrupt]' diff --git a/Demo/sgi/video/cam.py b/Demo/sgi/video/cam.py deleted file mode 100755 index fa8966f8b3..0000000000 --- a/Demo/sgi/video/cam.py +++ /dev/null @@ -1,129 +0,0 @@ -import sys -from socket import * -from gl import * -from GL import * -from DEVICE import * -from time import millitimer - -HS = 40 # Header size (must be same as in tv.py) - -# Rely on UDP packet (de)fragmentation for smoother images -# (Changed for broadcast) -MAX = 16000 - -PF = 2 # Default packfactor - -# Default receiver station is voorn. -# Kwik has no yellow pages, so... -HOST = '192.16.201.121' -PORT = 5555 - -if sys.argv[1:]: - PF = eval(sys.argv[1]) - -if sys.argv[2:]: - HOST = sys.argv[2] - if HOST == 'all': - HOST = '' - MAX = 1400 - -PF2 = PF*PF - -def main(): - centerx, centery = 400, 300 - - foreground() - wid = winopen('cam') - RGBmode() - doublebuffer() - gconfig() - qdevice(ESCKEY) - - w, h = getsize() - ortho2(0, w, 0, h) - w = w/PF*PF - h = h/PF*PF - - readsource(SRC_FRAMEGRABBER) - - s = socket(AF_INET, SOCK_DGRAM) - if HOST == '': - s.allowbroadcast(1) - addr = HOST, PORT - - bytesperline = w/PF2 - linesperchunk = MAX/bytesperline - linesperchunk = linesperchunk/PF*PF - nchunks = (h+linesperchunk-1)/linesperchunk - - print 'MAX=', MAX, - print 'linesperchunk=', linesperchunk, - print 'nchunks=', nchunks, - print 'w=', w, 'h=', h - - x1, x2 = 0, w-1 - - t1 = millitimer() - nframes = 0 - fps = 0 - - msg = '' - - while 1: - while qtest(): - dev, val = qread() - if dev == REDRAW: - reshapeviewport() - w, h = getsize() - ortho2(0, w, 0, h) - w = w/PF*PF - h = h/PF*PF - - bytesperline = w/PF2 - linesperchunk = MAX/bytesperline - linesperchunk = linesperchunk/PF*PF - nchunks = (h+linesperchunk-1)/linesperchunk - - print 'MAX=', MAX, - print 'linesperchunk=', linesperchunk, - print 'nchunks=', nchunks, - print 'w=', w, 'h=', h - - x1, x2 = 0, w-1 - - fps = 0 - - elif dev == ESCKEY: - winclose(wid) - return - - readsource(SRC_FRAMEGRABBER) - - nframes = nframes+1 - if nframes >= fps: - t2 = millitimer() - if t2 <> t1: - fps = int(10000.0*nframes/(t2-t1)) * 0.1 - msg = `fps` + ' frames/sec' - t1 = t2 - nframes = 0 - - RGBcolor(255,255,255) - cmov2i(9,9) - charstr(msg) - - swapbuffers() - rectcopy(centerx-w/2, centery-w/2, centerx+w/2, centery+w/2, 0, 0) - - for i in range(nchunks): - y1 = i*linesperchunk - y2 = y1 + linesperchunk-1 - if y2 >= h: y2 = h-1 - data = lrectread(x1, y1, x2, y2) - data2 = packrect(x2-x1+1, y2-y1+1, PF, data) - prefix = `w, h, PF, x1, y1, x2, y2` - prefix = prefix + ' ' * (HS-len(prefix)) - data3 = prefix + data2 - s.sendto(data3, addr) - -main() diff --git a/Demo/sgi/video/camcorder.py b/Demo/sgi/video/camcorder.py deleted file mode 100755 index 9b7618c436..0000000000 --- a/Demo/sgi/video/camcorder.py +++ /dev/null @@ -1,266 +0,0 @@ -from gl import * -from GL import * -from DEVICE import * -import time -import sys -import getopt -import socket -import posix -import vtime - -# Preallocation parameter -PREALLOC = 4 # Megabyte - -# Sync audio parameters -SYNCPORT = 10000 -CTLPORT = 10001 - -from vpregs import * - -class Struct(): pass -epoch = Struct() - -def getvideosize(): - w = getvideo(VP_WIDTH) - h = getvideo(VP_HEIGHT) - print 'WIDTH,HEIGHT:', w, h - print 'GB{X,Y}ORG:', getvideo(VP_GBXORG), getvideo(VP_GBYORG) - print 'FB{X,Y}ORG:', getvideo(VP_FBXORG), getvideo(VP_FBYORG) - x = 0 - y = 0 - return x,y,w,h - -framelist = [] - -def prealloc(w, h): - nbytes = w*h*4 - limit = PREALLOC*1024*1024 - total = 0 - list = [] - print 'Prealloc to', PREALLOC, 'Megabytes...' - while total+nbytes <= limit: - list.append('x'*nbytes) - total = total + nbytes - print 'Done.' - -def grabframe(f,x,y,w,h,pf): - readsource(SRC_FRONT) - if pf: - w = w/pf*pf - h = h/pf*pf - data = lrectread(x,y,x+w-1,y+h-1) - t = time.millitimer()-epoch.epoch - framelist.append(data, t) - readsource(SRC_FRAMEGRABBER) - -def saveframes(f, w, h, pf): - for data, t in framelist: - if pf: - w = w/pf*pf - h = h/pf*pf - data = packrect(w,h,pf,data) - f.write(`t` + ',' + `len(data)` + '\n') - f.write(data) - framelist[:] = [] - -def saveframe(f,x,y,w,h,pf, notime): - readsource(SRC_FRONT) - if pf: - w = w/pf*pf - h = h/pf*pf - data = lrectread(x,y,x+w-1,y+h-1) - if pf: data = packrect(w,h,pf,data) - if notime: t = 0 - else: t = time.millitimer()-epoch.epoch - f.write(`t` + ',' + `len(data)` + '\n') - f.write(data) - readsource(SRC_FRAMEGRABBER) - -def drawframe(x,y,w,h,col): - drawmode(OVERDRAW) - color(col) - bgnline() - v2i(x-1,y-1) ; v2i(x+w,y-1); v2i(x+w,y+h); v2i(x-1,y+h); v2i(x-1,y-1) - endline() - drawmode(NORMALDRAW) - -def usage(): - sys.stderr.write('Usage: camcorder ' + \ - '[-c] [-p packfactor] [-a audiomachine [-s]] [outputfile]\n') - sys.exit(2) - -def wrheader(f, w, h, pf): - f.write('CMIF video 1.0\n') - f.write(`w,h,pf` + '\n') - print 'width,height,pf:', w, h, pf, - if pf == 0: pf = 4 - print '(i.e.,', w*h*pf, 'bytes/frame)' - -def main(): - foreground() - pf = 2 - ausync = 0 - austart = 0 - optlist, args = getopt.getopt(sys.argv[1:],'ca:sp:') - for opt, arg in optlist: - if opt == '-c': - pf = 0 - elif opt == '-a': - ausync = 1 - aumachine = arg - elif opt == '-s': - austart = 1 - elif opt == '-p': - pf = int(eval(arg)) - else: - usage() - if args: - if len(args) > 1: - print 'Too many arguments' - usage() - filename = args[0] - else: - filename = 'film.video' - if austart: - if not ausync: - print 'Cannot use -s without -a' - usage() - print 'Starting audio recorder...' - posix.system('rsh '+aumachine+' syncrecord '+socket.gethostname()+' &') - if ausync: - print 'Syncing to audio recorder...' - globtime = vtime.VTime().init(1,aumachine,SYNCPORT) - ctl = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) - ctl.bind((socket.gethostname(),CTLPORT)) - aua = (socket.gethostbyname(aumachine), CTLPORT) - print 'Done.' - vidx, vidy, w, h = getvideosize() - #prefsize(w,h) - winx, winy = 1280-w-10, 1024-h-30 - prefposition(winx,winx+w-1,winy,winy+h-1) - win = winopen(filename) - f = open(filename, 'w') - w, h = getsize() - realw, realh = w, h - ####doublebuffer() - RGBmode() - gconfig() - qdevice(LEFTMOUSE) - qdevice(RKEY) - qdevice(SKEY) - qdevice(CKEY) - qdevice(PKEY) - qdevice(ESCKEY) - qdevice(WINQUIT) - qdevice(WINSHUT) - inrunning = 1 - outrunning = 0 - stop = 'stop' - readsource(SRC_FRAMEGRABBER) - mousing = 0 - epoch.epoch = time.millitimer() - stoptime = epoch.epoch - sizewritten = 0 - x, y = realw/4, realh/4 - w, h = w/2, h/2 - prealloc(w, h) - try: - drawframe(x,y,w,h,1) - nframe = 0 - num = 0 - while 1: - insingle = 0 - outsingle = 0 - if mousing: - drawframe(x,y,w,h,0) - ox, oy = getorigin() - if sizewritten: - x = getvaluator(MOUSEX)-ox - y = getvaluator(MOUSEY)-oy - else: - w = getvaluator(MOUSEX)-x-ox - h = getvaluator(MOUSEY)-y-oy - drawframe(x,y,w,h,1) - if qtest() or \ - not (mousing or inrunning or insingle or outrunning or outsingle): - ev, val = qread() - if ev == LEFTMOUSE and val == 1: - drawframe(x,y,w,h,0) - mousing = 1 - ox, oy = getorigin() - x = getvaluator(MOUSEX)-ox - y = getvaluator(MOUSEY)-oy - elif ev == LEFTMOUSE and val == 0: - if h < 0: - y, h = y+h, -h - if w < 0: - x, w = x+w, -w - mousing = 0 - if not sizewritten: - wrheader(f, w, h, pf) - sizewritten = 1 - prealloc(w, h) - elif ev == RKEY and val == 1: - if not inrunning: - ringbell() - else: - outrunning = 1 - wasstopped = time.millitimer() - stoptime - epoch.epoch = epoch.epoch + wasstopped - nframe = 0 - starttime = time.millitimer() - if ausync: - ctl.sendto(`(1,starttime)`, aua) - elif ev == PKEY and val == 1 and outrunning: - outrunning = 0 - stoptime = time.millitimer() - if ausync: - ctl.sendto(`(0,stoptime)`, aua) - fps = nframe * 1000.0 / (time.millitimer()-starttime) - print 'Recorded', nframe, - print 'frames at', 0.1*int(fps*10),'frames/sec' - print 'Saving...' - saveframes(f, w, h, pf) - print 'Done.' - elif ev == PKEY and val == 1 and not outrunning: - outsingle = 1 - elif ev == CKEY and val == 1: - inrunning = 1 - elif ev == SKEY and val == 1: - if outrunning: - ringbell() - elif inrunning: - inrunning = 0 - else: - insingle = 1 - elif ev in (ESCKEY, WINQUIT, WINSHUT): - if ausync: - ctl.sendto(`(2,time.millitimer())`, aua) - raise stop - elif ev == REDRAW: - drawframe(x,y,w,h,0) - reshapeviewport() - drawframe(x,y,w,h,1) - if inrunning or insingle: - if outrunning: - rectcopy(vidx+x,vidy+y,vidx+x+w-1,vidy+y+h-1,x,y) - else: - rectcopy(vidx,vidy,vidx+realw-1,vidx+realh-1,0,0) - ####swapbuffers() - if outrunning or outsingle: - nframe = nframe + 1 - if not sizewritten: - wrheader(f, w, h, pf) - sizewritten = 1 - if outrunning: - grabframe(f, x, y, w, h, pf) - else: - saveframe(f, x, y, w, h, pf, outsingle) - except stop: - pass - finally: - drawmode(OVERDRAW) - color(0) - clear() - -main() diff --git a/Demo/sgi/video/colorsys.py b/Demo/sgi/video/colorsys.py deleted file mode 100755 index dd3a033b26..0000000000 --- a/Demo/sgi/video/colorsys.py +++ /dev/null @@ -1,106 +0,0 @@ -# -# Module color - do color conversions -# - -ONE_THIRD=1.0/3.0 -ONE_SIXTH=1.0/6.0 -TWO_THIRD=2.0/3.0 - -def rgb_to_yiq(r,g,b): - y = 0.3*r + 0.59*g + 0.11*b - i = 0.6*r - 0.28*g - 0.32*b - q = 0.21*r- 0.52*g + 0.31*b - return (y,i,q) -def yiq_to_rgb(y,i,q): - r = y + 0.948262*i + 0.624013*q - g = y - 0.276066*i - 0.639810*q - b = y - 1.105450*i + 1.729860*q - if r < 0.0: r = 0.0 - if g < 0.0: g = 0.0 - if b < 0.0: b = 0.0 - if r > 1.0: r = 1.0 - if g > 1.0: g = 1.0 - if b > 1.0: b = 1.0 - return (r,g,b) - -def _v(m1,m2,hue): - if hue >= 1.0: hue = hue - 1.0 - if hue < 0.0: hue = hue + 1.0 - if hue < ONE_SIXTH: - return m1 + (m2-m1)*hue*6.0 - if hue < 0.5: - return m2 - if hue < TWO_THIRD: - return m1 + (m2-m1)*(TWO_THIRD-hue)*6.0 - return m1 - -def rgb_to_hls(r,g,b): - maxc = max(r,g,b) - minc = min(r,g,b) - l = (minc+maxc)/2.0 - if minc == maxc: - return 0.0, l, 0.0 - if l <= 0.5: - s = (maxc-minc)/(maxc+minc) - else: - s = (maxc-minc)/(2-maxc-minc) - rc = (maxc-r)/(maxc-minc) - gc = (maxc-g)/(maxc-minc) - bc = (maxc-b)/(maxc-minc) - if r == maxc: - h = bc-gc - elif g == maxc: - h = 2.0+rc-bc - else: - h = 4.0+gc-rc - h = h/6.0 - if h < 0.0: - h = h + 1.0 - return h,l,s -def hls_to_rgb(h,l,s): - if s == 0.0: - return l,l,l - if l <= 0.5: - m2 = l * (1.0+s) - else: - m2 = l+s-(l*s) - m1 = 2.0*l - m2 - return (_v(m1,m2,h+ONE_THIRD), _v(m1,m2,h), _v(m1,m2,h-ONE_THIRD)) - -def rgb_to_hsv(r,g,b): - maxc = max(r,g,b) - minc = min(r,g,b) - v = maxc - if minc == maxc: - return 0.0, 0.0, v - s = (maxc-minc)/maxc - rc = (maxc-r)/(maxc-minc) - gc = (maxc-g)/(maxc-minc) - bc = (maxc-b)/(maxc-minc) - if r == maxc: - h = bc-gc - elif g == maxc: - h = 2.0+rc-bc - else: - h = 4.0+gc-rc - h = h/6.0 - if h < 0.0: - h = h + 1.0 - return h,s,v -def hsv_to_rgb(h,s,v): - if s == 0.0: - return v,v,v - i = int(h*6.0) - f = (h*6.0)-i - p = v*(1.0-s) - q = v*(1.0-s*f) - t = v*(1.0-s*(1.0-f)) - if i in (0,6): return v,t,p - if i == 1: return q,v,p - if i == 2: return p,v,t - if i == 3: return p,q,v - if i == 4: return t,p,v - if i == 5: return v,p,q - print i, h, f - print h, s, v - raise 'Bad color' diff --git a/Demo/sgi/video/i2v.c b/Demo/sgi/video/i2v.c deleted file mode 100755 index 21dfabe2b2..0000000000 --- a/Demo/sgi/video/i2v.c +++ /dev/null @@ -1,80 +0,0 @@ -/* - * i2v -- image-to-video. - * Convert an SGI image file to a format that is immediately usable - * by lrectwrite. - * The header of the file contains a description (in ASCII) - * padded to 8196 byte for fast access of the rest of the file. - * - * Based upon "showimg.c" by Paul Haeberli. - * --Guido van Rossum, CWI, Amsterdam - */ -#include -#include -#include -#include - -unsigned short rs[8192]; -unsigned short gs[8192]; -unsigned short bs[8192]; - -IMAGE *image; -int xsize, ysize, zsize; -FILE *fp; - -char header[100]; -char *progname = "i2v"; - -main(argc,argv) -int argc; -char **argv; -{ - int y; - if (argc > 0) progname = argv[0]; - if( argc != 3 ) { - fprintf(stderr, "usage: %s infile outfile\n", progname); - exit(2); - } - if( (image=iopen(argv[1],"r")) == NULL ) { - fprintf(stderr, "%s: can't open input file %s\n",progname, argv[1]); - exit(1); - } - xsize = image->xsize; - ysize = image->ysize; - zsize = image->zsize; - if ((fp = fopen(argv[2], "w")) == NULL) { - fprintf(stderr,"%s: can't open output file %s\n", progname, argv[2]); - exit(1); - } - fprintf(fp, "CMIF video 1.0\n"); - fprintf(fp, "(%d, %d, %d)\n", xsize, ysize, 0); - fprintf(fp, "0, %ld\n", (long)xsize * (long)ysize * sizeof(long)); - fflush(fp); - for(y = 0; y < ysize; y++) { - if(zsize<3) { - getrow(image, rs, y, 0); - writepacked(xsize, rs, rs, rs); - } else { - getrow(image, rs, y, 0); - getrow(image, gs, y, 1); - getrow(image, bs, y, 2); - writepacked(xsize, rs, gs, bs); - } - } - exit(0); -} - -writepacked(n, rsptr, gsptr, bsptr) - int n; - short *rsptr, *gsptr, *bsptr; -{ - long parray[8192]; - long *pptr = parray; - int i = n; - while (--i >= 0) { - *pptr++ = *rsptr++ | (*gsptr++<<8) | (*bsptr++<<16); - } - if (fwrite((char *) parray, sizeof(long), n, fp) != n) { - perror("fwrite"); - exit(1); - } -} diff --git a/Demo/sgi/video/makemovie.py b/Demo/sgi/video/makemovie.py deleted file mode 100755 index 5cb41cde2e..0000000000 --- a/Demo/sgi/video/makemovie.py +++ /dev/null @@ -1,218 +0,0 @@ -#! /ufs/guido/bin/sgi/python -#! /ufs/guido/src/video/py - -# Capture a CMIF movie using the Indigo video library and board - - -# Usage: -# -# makemovie [-q queuesize] [-t recordtime] [-a] [moviefile [audiofile]] - - -# Options: -# -# -q queuesize : set the capture queue size (default and max 16) -# -t recordtime : set the record time in seconds (default 5 seconds) -# -a : record audio as well -# moviefile : here goes the movie data (default film.video); -# the format is documented in cmif-film.ms -# audiofile : with -a, here goes the audio data (default film.aiff); -# audio data is recorded in AIFF format, using the -# input sampling rate, source and volume set by the -# audio panel, in mono, 8 bits/sample - - -# User interface: -# -# Start the application. Resize the window to the desired movie size. -# Click the left mouse button to start recording (recording starts -# when you release the mouse button). Recording time is specified by -# the -t option (XXX this should change). -# -# Press ESC or select the window manager Quit or Close window option -# to quit. (You can do this without recording -- then the output -# files are untouched.) -# -# (It is possible to record more than once; but this doesn't set the -# time stamps correctly yet, and doesn't work at all with audio. So -# don't use.) - - -# XXX To do: -# -# fix timestamps for second and further recordings -# fix audio " " " " " -# flush audio buffer when recording starts -# make code more readable - - -import sys -sys.path.append('/ufs/guido/src/video') -import sv, SV -import VFile -import gl, GL, DEVICE -import al, AL -import time -import posix -import getopt -import string - - -def main(): - QSIZE = 16 - TIME = 5 - audio = 0 - - opts, args = getopt.getopt(sys.argv[1:], 'aq:t:') - for opt, arg in opts: - if opt == '-a': - audio = 1 - elif opt == '-q': - QSIZE = string.atoi(arg) - elif opt == '-t': - TIME = string.atoi(arg) - - if args: - filename = args[0] - else: - filename = 'film.video' - - if audio: - if args[1:]: - audiofilename = args[1] - else: - audiofilename = 'film.aiff' - - gl.foreground() - - x, y = SV.PAL_XMAX / 4, SV.PAL_YMAX / 4 - print x, 'x', y - - gl.minsize(40, 30) - gl.stepunit(8, 6) - gl.maxsize(SV.PAL_XMAX, SV.PAL_YMAX) - gl.keepaspect(SV.PAL_XMAX, SV.PAL_YMAX) - win = gl.winopen(filename) - x, y = gl.getsize() - print x, 'x', y - - v = sv.OpenVideo() - v.BindGLWindow(win, SV.IN_REPLACE) - v.SetSize(x, y) - v.BindGLWindow(win, SV.IN_REPLACE) - - v.SetCaptureFormat(SV.RGB_FRAMES) - v.SetCaptureMode(SV.BLOCKING_CAPTURE) - v.SetQueueSize(QSIZE) - v.InitCapture() - if v.GetQueueSize() != QSIZE: - QSIZE = v.GetQueueSize() - print 'Warning: QSIZE reduced to', QSIZE - - gl.qdevice(DEVICE.LEFTMOUSE) - gl.qdevice(DEVICE.WINQUIT) - gl.qdevice(DEVICE.WINSHUT) - gl.qdevice(DEVICE.ESCKEY) - - print 'Click left mouse to start recording', TIME, 'seconds' - ofile = None - afile = None - # Mouse down opens the file & freezes window - # Mouse up starts recording frames - - while 1: - dev, val = gl.qread() - if dev == DEVICE.LEFTMOUSE: - # Start recording - if val == 1: - # Mouse down -- preparations - if ofile == None: - ofile = VFile.VoutFile().init(filename) - ofile.format = 'rgb8' - ofile.width = x - ofile.height = y - ofile.writeheader() - # XXX other format bits? - # The window can't be resized from now - gl.prefsize(x, y) - gl.winconstraints() - gl.wintitle('* ' + filename) - if audio: - afile = initaudio(audiofilename) - continue - # Mouse up -- start actual recording - global recording, stop_recording - if audio: - stop_recording = 0 - recording.release() - t0 = time.millitimer() - v.StartCapture() - while 1: - t = time.millitimer() - t0 - if t >= TIME*1000: - break - if v.GetCaptured() > 2: - doframe(v, ofile, x, y, t) - v.StopCapture() - stop_recording = 1 - while v.GetCaptured() > 0: - doframe(v, ofile, x, y, t) - t = time.millitimer() - t0 - gl.wintitle(filename) - elif dev == DEVICE.REDRAW: - # Window resize (or move) - x, y = gl.getsize() - print x, 'x', y - v.SetSize(x, y) - v.BindGLWindow(win, SV.IN_REPLACE) - elif dev in (DEVICE.ESCKEY, DEVICE.WINQUIT, DEVICE.WINSHUT): - # Quit - if ofile: - ofile.close() - if afile: - afile.destroy() - posix._exit(0) - # EndCapture dumps core... - v.EndCapture() - v.CloseVideo() - gl.winclose(win) - -def doframe(v, ofile, x, y, t): - cd, start = v.GetCaptureData() - data = cd.interleave(x, y) - cd.UnlockCaptureData() - ofile.writeframe(t, data, None) - -AQSIZE = 16000 - -def initaudio(filename): - import thread, aiff - global recording, stop_recording - afile = aiff.Aiff().init(filename, 'w') - afile.nchannels = AL.MONO - afile.sampwidth = AL.SAMPLE_8 - params = [AL.INPUT_RATE, 0] - al.getparams(AL.DEFAULT_DEVICE, params) - print 'rate =', params[1] - afile.samprate = params[1] - c = al.newconfig() - c.setchannels(AL.MONO) - c.setqueuesize(AQSIZE) - c.setwidth(AL.SAMPLE_8) - aport = al.openport(filename, 'r', c) - recording = thread.allocate_lock() - recording.acquire() - stop_recording = 0 - thread.start_new_thread(recorder, (afile, aport)) - return afile - -def recorder(afile, aport): - # XXX recording more than one fragment doesn't work - # XXX (the thread never dies) - recording.acquire() - while not stop_recording: - data = aport.readsamps(AQSIZE/2) - afile.writesampsraw(data) - del data - -main() diff --git a/Demo/sgi/video/squash.c b/Demo/sgi/video/squash.c deleted file mode 100755 index d5ea946924..0000000000 --- a/Demo/sgi/video/squash.c +++ /dev/null @@ -1,130 +0,0 @@ -#include - -long *bm; -long h, w; -long factor; - -#define OC(x,xi) ((x)*factor+(xi)) -#define BM(x,xi,y,yi) bm[OC(y,yi)*w+OC(x,xi)] - -#define COMP(r,g,b) ((r) | ((g)<<8) | ((b) << 16)) - -#define R(comp) ((comp) & 0xff) -#define G(comp) (((comp)>>8) & 0xff) -#define B(comp) (((comp)>>16) & 0xff) - -main(argc, argv) - char **argv; -{ - char lbuf[100]; - int nh, nw; - int x, y, xi, yi; - int num; - int r, g, b; - long data; - long *nbm, *nbmp; - int i; - int bits, mask, roundbit, addbit; - int pf; - int newfmt = 0; - - if( argc != 2 && argc != 3) { - fprintf(stderr, "Usage: squash factor [bits]\n"); - exit(1); - } - factor = atoi(argv[1]); - if ( argc > 2 ) { - bits = atoi(argv[2]); - mask = (1 << bits) - 1; - mask <<= (8-bits); - roundbit = 1 << (7-bits); - addbit = 1 << (8-bits); - fprintf(stderr, "%x %x %x\n", mask, roundbit, addbit); - } else { - mask = 0xff; - roundbit = 0; - addbit = 0; - } - gets(lbuf); - if ( strncmp( lbuf, "CMIF", 4) == 0 ) { - newfmt = 1; - gets(lbuf); - if( sscanf(lbuf, "(%d,%d,%d)", &w, &h, &pf) != 3) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - if ( pf != 0 ) { - fprintf(stderr, "%s: packed file\n", argv[0]); - exit(1); - } - } else { - if ( sscanf(lbuf, "(%d,%d)", &w, &h) != 2) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - } - nh = h / factor; - nw = w / factor; - if ( newfmt ) - printf("CMIF video 1.0\n(%d,%d,%d)\n", nw, nh, 0); - else - printf("(%d,%d)\n", nw, nh); - if ( (bm = (long *)malloc(h*w*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - if ( (nbm = (long *)malloc(nh*nw*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - while( !feof(stdin) ) { - { int t, s; - gets(lbuf); - if ( feof(stdin) ) break; - if ( sscanf(lbuf, "%d,%d", &t,&s) == 2) { - if ( s != h*w*4 ) { - fprintf(stderr, "Size changed from %d to %d: %s\n",4*h*w,s, lbuf); - exit(1); - } - printf("%d, %d\n", t, nh*nw*4); - } else { - puts(lbuf); - } - } - fprintf(stderr, "Reading %d\n", h*w*sizeof(long)); - if ( (i=fread(bm, 1, h*w*sizeof(long), stdin)) != h*w*sizeof(long)) { - fprintf(stderr, "%s: short read, %d wanted %d\n", argv[0], - i, h*w*sizeof(long)); - exit(1); - } - nbmp = nbm; - for( y=0; y - -long *bm; -long h, w; -long factor; - -#define OC(x,xi) ((x)*factor+(xi)) -#define BM(x,xi,y,yi) bm[OC(y,yi)*w+OC(x,xi)] - -#define COMP(r,g,b) ((r) | ((g)<<8) | ((b) << 16)) - -#define R(comp) ((comp) & 0xff) -#define G(comp) (((comp)>>8) & 0xff) -#define B(comp) (((comp)>>16) & 0xff) - -main(argc, argv) - char **argv; -{ - char lbuf[100]; - int nh, nw; - int x, y, xi, yi; - int num; - int r, g, b; - long data; - long *nbm, *nbmp; - int i; - - if( argc != 2) { - fprintf(stderr, "Usage: squash factor\n"); - exit(1); - } - factor = atoi(argv[1]); - gets(lbuf); - if ( sscanf(lbuf, "(%d,%d)", &w, &h) != 2) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - nh = h / factor; - nw = w / factor; - printf("(%d,%d)\n", nw, nh); - if ( (bm = (long *)malloc(h*w*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - if ( (nbm = (long *)malloc(nh*nw*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - while( !feof(stdin) ) { - gets(lbuf); - if ( feof(stdin) ) break; - puts(lbuf); - fprintf(stderr, "Reading %d\n", h*w*sizeof(long)); - if ( (i=fread(bm, 1, h*w*sizeof(long), stdin)) != h*w*sizeof(long)) { - fprintf(stderr, "%s: short read, %d wanted %d\n", argv[0], - i, h*w*sizeof(long)); - exit(1); - } - nbmp = nbm; - for( y=0; y size: - raise EOFError - dostat(w2, h2, data) - nframes = nframes+1 - t1 = millitimer() - - t = 0.001 * (t1-t0) - fps = 0.1 * int(10*nframes/t) - print nframes, 'frames in', t, 'sec. =', fps, 'frames/sec.' - -def dostat(w, h, data): - print - stat3(w, h, data) - -# Statistic op 1: frequencies of byte values -def stat1(w, h, data): - bins = [0]*256 - for c in data: - i = ord(c) - bins[i] = bins[i]+1 - prbins(bins) - -def prbins(bins): - import string - s = '' - tot = 0 - for i in range(256): - tot = tot + bins[i] - s = s + string.rjust(`bins[i]`, 4) - if len(s) >= 4*16: - print s, string.rjust(`tot`, 7) - s = '' - tot = 0 - -# Statistic op 2: run lengths -def stat2(w, h, data): - runs = [] - for y in range(h): - count, value = 0, ord(data[y*w]) - for c in data[y*w : y*w+w]: - i = ord(c) - if i <> value: - runs.append(count, value) - count, value = 0, i - count = count+1 - runs.append(count, value) - print len(runs), 'runs =', 0.1 * (10*w*h/len(runs)), 'bytes/run' - -# Statistic op 3: frequencies of byte differences -def stat3(w, h, data): - bins = [0]*256 - prev = 0 - for c in data: - i = ord(c) - delta = divmod(i-prev, 256)[1] - prev = i - bins[delta] = bins[delta]+1 - prbins(bins) - -# Try packing -def packblock(w, h, data): - res = '' - for y in range(h): - res = res + packline(data[y*w : y*w+w]) - return res - -def packline(line): - bytes = [] - for c in line: - bytes.append(ord(c)) - prev = bytes[0] - i, n = 1, len(bytes) - while i < n: - for pack in (0, 2, 4, 8): - if pack == 0: - lo, hi = 0, 0 - else: - hi = pow(2, pack-1)-1 - lo = -hi-1 - p = prev - j = i - count = 0 - while j < n: - x = bytes[j] - delta = byte(x-p) - if not lo <= delta <= hi: - break - p = x - j = j+1 - -def byte(x): return divmod(x, 256)[1] - -main() diff --git a/Demo/sgi/video/syncaudio.py b/Demo/sgi/video/syncaudio.py deleted file mode 100755 index fd09d2879c..0000000000 --- a/Demo/sgi/video/syncaudio.py +++ /dev/null @@ -1,94 +0,0 @@ -import AL -import al -import sys -import vtime -import socket -import time - - -SLEEPTIME = 500 # 500 ms sleeps -SAMPLEFREQ = 16000 # 16Khz samples -SAMPLERATE = AL.RATE_16000 -NEEDBUFFERED = SAMPLEFREQ # Buffer 1 second of sound -BUFFERSIZE = NEEDBUFFERED*4 # setqueuesize() par for 2 second sound - -AVSYNCPORT = 10000 # Port for time syncing -AVCTLPORT = 10001 # Port for record start/stop - -def main(): - if len(sys.argv) <> 3: - print 'Usage: ', sys.argv[0], 'videohostname soundfile' - sys.exit(1) - # - ofile = open(sys.argv[2], 'w') - # - globaltime = vtime.VTime().init(0,sys.argv[1],AVSYNCPORT) - # - ctl = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) - ctl.bind((socket.gethostname(),AVCTLPORT)) - # - inp = openmic() - # - out = 0 # Open aiff file - # - while 1: - if mainloop(None, ctl, inp, out, globaltime): - break - if mainloop(ofile, ctl, inp, out, globaltime): - break - pass # Close aiff file - sys.exit(0) -# -def openmic(): - conf = al.newconfig() - conf.setqueuesize(BUFFERSIZE) - conf.setwidth(AL.SAMPLE_16) - conf.setchannels(AL.MONO) - return al.openport('micr','r',conf) -# -def mainloop(ofile, ctl, inp, out, globaltime): - # - # Wait for sync packet, keeping 1-2 seconds of sound in the - # buffer - # - totsamps = 0 - totbytes = 0 - starttime = time.millitimer() - while 1: - time.millisleep(SLEEPTIME) - if ctl.avail(): - break - nsamples = inp.getfilled()-NEEDBUFFERED - if nsamples>0: - data = inp.readsamps(nsamples) - totsamps = totsamps + nsamples - totbytes = totbytes + len(data) - if ofile <> None: - ofile.write(data) - # - # Compute his starttime and the timestamp of the first byte in the - # buffer. Discard all buffered data upto his starttime - # - startstop,histime = eval(ctl.recv(100)) - if (ofile == None and startstop == 0) or \ - (ofile <> None and startstop == 1): - print 'Sync error: saving=',save,' request=',startstop - sys.exit(1) - filllevel = inp.getfilled() - filltime = time.millitimer() - filltime = filltime - filllevel / (SAMPLEFREQ/1000) - starttime = globaltime.his2mine(histime) - nsamples = starttime - filltime - if nsamples < 0: - print 'Start/stop signal came too late' - sys.exit(1) - nsamples = nsamples * (SAMPLEFREQ / 1000) - data = inp.readsamps(nsamples) - totsamps = totsamps + nsamples - totbytes = totbytes + len(data) - print 'Time: ', time.millitimer()-starttime, ', Bytes: ', totbytes, ', Samples: ', totsamps - if ofile <> None: - ofile.write(data) - return (startstop == 2) - -main() diff --git a/Demo/sgi/video/tomono.c b/Demo/sgi/video/tomono.c deleted file mode 100755 index 546af68afd..0000000000 --- a/Demo/sgi/video/tomono.c +++ /dev/null @@ -1,165 +0,0 @@ -#include - -long *bm; -long *nbm; -long h, w; -int nh, nw; -long factor; - -#define OC(x,xi) ((x)*factor+(xi)) -#define BM(x,xi,y,yi) bm[OC(y,yi)*w+OC(x,xi)] - -#define COMP(r,g,b) ((r) | ((g)<<8) | ((b) << 16)) - -#define R(comp) ((comp) & 0xff) -#define G(comp) (((comp)>>8) & 0xff) -#define B(comp) (((comp)>>16) & 0xff) - -#define CHOICEFUNC(np1, np2) ( random() & 1 ) - -int inlevels = 3*255; -int outlevels = 1; - -main(argc, argv) - char **argv; -{ - char lbuf[100]; - int x, y, xi, yi; - int num; - int r, g, b; - long data; - int i; - double greyness; - int inpixels, outpixels; - int resid; - - setvbuf(stdout, 0, _IOFBF, 1024*128); - if( argc != 2) { - fprintf(stderr, "Usage: tomono factor\n"); - exit(1); - } - factor = atoi(argv[1]); - gets(lbuf); - if ( sscanf(lbuf, "(%d,%d)", &w, &h) != 2) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - nh = h / factor; - nw = w / factor; - printf("(%d,%d)\n", nw, nh); - if ( (bm = (long *)malloc(h*w*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - if ( (nbm = (long *)malloc(nh*nw*sizeof(long))) == 0) { - fprintf(stderr, "%s: No memory\n", argv[0]); - exit(1); - } - while( !feof(stdin) ) { - gets(lbuf); - if ( feof(stdin) ) break; - puts(lbuf); - fprintf(stderr, "Reading %d\n", h*w*sizeof(long)); - if ( (i=fread(bm, 1, h*w*sizeof(long), stdin)) != h*w*sizeof(long)) { - fprintf(stderr, "%s: short read, %d wanted %d\n", argv[0], - i, h*w*sizeof(long)); - exit(1); - } - /* - ** Compute picture blackness. - */ - inpixels = 0; - inpixels = countpixels(0,0,w,h); - greyness = (double)inpixels/(h*w*inlevels); - fprintf(stderr, "%3.1f%% grey\n", 100.0*greyness); - outpixels = (int)(greyness*outlevels*nh*nw); - fprintf(stderr, "Inpixels: %d (%d) Outpixels %d\n", inpixels, inpixels/inlevels, outpixels); - resid = fillpixels(0,0,nw,nh,0,0,w,h,outpixels); - if ( resid > 1 ) fprintf(stderr, "Residue: %d pixels\n", resid); - fprintf(stderr, "Writing %d\n", (nh*nw)*sizeof(long)); - fwrite(nbm, 1, (nh*nw)*sizeof(long), stdout); - } - exit(0); -} - -countpixels(x0,y0,x1,y1) -{ - int x, y, tot, data; - - tot = 0; - for( y=y0; y= x1 && y0+1 >= y1 ) { - if ( npixels ) { - nbm[y0*nw+x0] = 0xffffff; -/* fprintf(stderr, "->%d,%d\n", x0,y0); */ - return npixels - 1; - } - return 0; - } - if ( x1-x0 < y1-y0 ) { - if ( y1 - y0 <= 2 ) - m = y0 + 1; - else - m = y0+1+(random()%(y1-y0-1)); -/* fprintf(stderr,"%d,%d %d,%d Y %d\n", x0, x1, y0, y1, m); */ - /* om = (oy0+oy1)/2; */ om = m; - p1 = countpixels(ox0,oy0,ox1,om); - p2 = countpixels(ox0,om,ox1,oy1); - np1 = (int)(((float)p1/(p1+p2))*npixels); - np2 = (int)(((float)p2/(p1+p2))*npixels); - rp = npixels - np1 - np2; - if ( rp ) { - np1 += rp/2; - rp = rp - rp/2; - np2 += rp; - } - resid = 0; - if ( CHOICEFUNC(np1, np2) ) { - resid = fillpixels(x0,y0,x1,m,ox0,oy0,ox1,om,np1+resid); - resid = fillpixels(x0,m,x1,y1,ox0,om,ox1,oy1,np2+resid); - } else { - resid = fillpixels(x0,m,x1,y1,ox0,om,ox1,oy1,np2+resid); - resid = fillpixels(x0,y0,x1,m,ox0,oy0,ox1,om,np1+resid); - } - } else { - if ( x1 - x0 <= 2 ) - m = x0 + 1; - else - m = x0+1+(random()%(x1-x0-1)); -/* fprintf(stderr,"%d,%d %d,%d X %d\n", x0, x1, y0, y1, m); */ - /* om = (ox0+ox1)/2; */ om = m; - p1 = countpixels(ox0,oy0,om,oy1); - p2 = countpixels(om,oy0,ox1,oy1); - np1 = (int)(((float)p1/(p1+p2))*npixels); - np2 = (int)(((float)p2/(p1+p2))*npixels); - rp = npixels - np1 - np2; - if ( rp ) { - np1 += rp/2; - rp = rp - rp/2; - np2 += rp; - } - resid = 0; - if ( CHOICEFUNC(np1, np2) ) { - resid = fillpixels(x0,y0,m,y1,ox0,oy0,om,oy1,np1+resid); - resid = fillpixels(m,y0,x1,y1,om,oy0,ox1,oy1,np2+resid); - } else { - resid = fillpixels(m,y0,x1,y1,om,oy0,ox1,oy1,np2+resid); - resid = fillpixels(x0,y0,m,y1,ox0,oy0,om,oy1,np1+resid); - } - } - return resid; -} diff --git a/Demo/sgi/video/tv.py b/Demo/sgi/video/tv.py deleted file mode 100755 index da4bacbb63..0000000000 --- a/Demo/sgi/video/tv.py +++ /dev/null @@ -1,79 +0,0 @@ -import string - -from socket import * -from gl import * -from GL import * -from DEVICE import * -from time import millisleep, millitimer - -PORT = 5555 - -PF = 2 # packfactor -HS = 40 # Header size - -def testimage(): - RGBcolor(0, 0, 0) - clear() - RGBcolor(0, 255, 0) - cmov2i(10, 10) - charstr('Waiting...') - -def reshape(): - reshapeviewport() - w, h = getsize() - ortho2(0, w, 0, h) - testimage() - return w, h - -def main(): - s = socket(AF_INET, SOCK_DGRAM) - s.bind('', PORT) - - foreground() - wid = winopen('tv') - RGBmode() - gconfig() - qdevice(ESCKEY) - - oldw, oldh = getsize() - ortho2(0, oldw, 0, oldh) - testimage() - - t1 = millitimer() - - while 1: - if qtest(): - dev, val = qread() - if dev == ESCKEY: - winclose(wid) - return - elif dev == REDRAW: - oldw, oldh = reshape() - elif s.avail(): - data = s.recv(17000) - header = string.strip(data[:HS]) - w, h, pf, x1, y1, x2, y2 = eval(header) - if (w, h) <> (oldw, oldh): - x, y = getorigin() - x, y = x-1, y+21 # TWM correction - winposition(x, x+w-1, y+oldh-h, y+oldh-1) - oldw, oldh = reshape() - data2 = data[HS:] - dx = (x2-x1+1)/pf - dy = (y2-y1+1)/pf - data3 = unpackrect(dx, dy, 1, data2) - rectzoom(pf, pf) - lrectwrite(x1, y1, x1+dx-1, y1+dy-1, data3) - t1 = millitimer() - else: - t2 = millitimer() - if t2-t1 >= 5000: - testimage() - t1 = t2 - else: - millisleep(10) - - winclose(wid) - return data - -main() diff --git a/Demo/sgi/video/v2i.c b/Demo/sgi/video/v2i.c deleted file mode 100755 index 5f8f3b5dec..0000000000 --- a/Demo/sgi/video/v2i.c +++ /dev/null @@ -1,79 +0,0 @@ -/* Convert the first image of a CMIF video movie file to SGI .rgb format. - usage: v2i videofile imagefile [planemask] - link with -limage -*/ - -#include -#include - -long bm[1280]; -short rb[1280], gb[1280], bb[1280]; -long w, h, pf; - -#define R(comp) ((comp) & 0xff) -#define G(comp) (((comp)>>8) & 0xff) -#define B(comp) (((comp)>>16) & 0xff) - -main(argc, argv) - char **argv; -{ - char lbuf[100]; - int x, y; - int i; - IMAGE * of; - int pmask; - - if( argc != 3 && argc != 4) { - fprintf(stderr, "Usage: v2i videofile imgfile [planemask]\n"); - exit(2); - } - if ( argc == 4) - pmask = atoi(argv[3]); - else - pmask = 7; - if ( freopen(argv[1], "r", stdin) == NULL ) { - perror(argv[1]); - exit(1); - } - if (fgets(lbuf, sizeof lbuf, stdin) == NULL) { - fprintf(stderr, "Immediate EOF\n"); - exit(1); - } - if (strncmp(lbuf, "CMIF", 4) == 0) { - /* Skip optional header line */ - if (fgets(lbuf, sizeof lbuf, stdin) == NULL) { - fprintf(stderr, "Immediate EOF after header\n"); - exit(1); - } - } - pf = 2; /* Default */ - if ( sscanf(lbuf, "(%d,%d,%d)", &w, &h, &pf) < 2) { - fprintf(stderr, "%s: bad size spec: %s\n", argv[0], lbuf); - exit(1); - } - fgets(lbuf, sizeof lbuf, stdin); /* Skip time info */ - if ( w > 1280 ) { - fprintf(stderr, "%s: Sorry, too wide\n", argv[0]); - exit(1); - } - if ( (of=iopen(argv[2], "w", RLE(1), 3, w, h, 3)) == 0) { - perror(argv[2]); - exit(1); - } - for( y=0; y 2: - usage() - [ifile, ofile] = args - print 'open film ', ifile - ifilm = VFile.VinFile().init(ifile) - print 'open output ', ofile - ofilm = VFile.VoutFile().init(ofile) - - ofilm.setinfo(ifilm.getinfo()) - - use_grabber = 0 - continuous = 0 - tomono = 0 - tomonodither = 0 - for o, a in opts: - if o == '-t': - ofilm.format = a - use_grabber = 1 - if o == '-a': - continuous = 1 - if o == '-m': - if ifilm.format <> 'grey': - print '-m only supported for greyscale' - sys.exit(1) - tomono = 1 - treshold = string.atoi(a) - ofilm.format = 'mono' - if o == '-d': - if ifilm.format <> 'grey': - print '-m only supported for greyscale' - sys.exit(1) - tomonodither = 1 - ofilm.format = 'mono' - - ofilm.writeheader() - # - prefsize(ifilm.width, ifilm.height) - w = winopen(ifile) - qdevice(KEYBD) - qdevice(ESCKEY) - qdevice(WINQUIT) - qdevice(WINSHUT) - print 'qdevice calls done' - # - help() - # - time, data, cdata = ifilm.getnextframe() - ifilm.showframe(data, cdata) - iframe = 1 - report(time, iframe) - # - while 1: - if continuous: - dev = KEYBD - else: - dev, val = qread() - if dev in (ESCKEY, WINQUIT, WINSHUT): - break - if dev == REDRAW: - reshapeviewport() - elif dev == KEYBD: - if continuous: - c = '0' - else: - c = chr(val) - #XXX Debug - if c == 'R': - c3i(255,0,0) - clear() - if c == 'G': - c3i(0,255,0) - clear() - if c == 'B': - c3i(0,0,255) - clear() - if c == 'w' or continuous: - if use_grabber: - data, cdata = ofilm.grabframe() - if tomono: - data = imageop.grey2mono(data, \ - ifilm.width, ifilm.height, \ - treshold) - if tomonodither: - data = imageop.dither2mono(data, \ - ifilm.width, ifilm.height) - ofilm.writeframe(time, data, cdata) - print 'Frame', iframe, 'written.' - if c == 'n' or continuous: - try: - time,data,cdata = ifilm.getnextframe() - ifilm.showframe(data, cdata) - iframe = iframe+1 - report(time, iframe) - except EOFError: - print 'EOF' - if continuous: - break - ringbell() - elif dev == INPUTCHANGE: - pass - else: - print '(dev, val) =', (dev, val) - ofilm.close() - -main() diff --git a/Demo/sgi/video/video.py b/Demo/sgi/video/video.py deleted file mode 100755 index 1b81bd83f7..0000000000 --- a/Demo/sgi/video/video.py +++ /dev/null @@ -1,218 +0,0 @@ -import getopt -from gl import * -from GL import * -from DEVICE import * -import time -import sys -import al -import AL - -sys.path.append('/ufs/guido/src/video') # Increase chance to find colorsys -import colorsys - -BUFFERSIZE = 32000 - -class Struct(): pass -epoch = Struct() -epoch.correcttiming = 1 -EndOfFile = 'End of file' -bye = 'bye' - -def openspkr(): - conf = al.newconfig() - conf.setqueuesize(BUFFERSIZE) - conf.setwidth(AL.SAMPLE_16) - conf.setchannels(AL.MONO) - return al.openport('spkr','w',conf) - -def openvideo(name): - try: - f = open(name, 'r') - except: - sys.stderr.write(name + ': cannot open\n') - sys.exit(1) - line = f.readline() - if not line: raise EndOfFile - colorinfo = (8, 0, 0, 0) - if line[:4] == 'CMIF': - if line[:14] == 'CMIF video 2.0': - line = f.readline() - colorinfo = eval(line[:-1]) - line = f.readline() - x = eval(line[:-1]) - if len(x) == 3: w, h, pf = x - else: w, h = x; pf = 2 - if pf and w/pf % 4 <> 0: - sys.stderr.write( \ - 'warning: stride not a multiple of 4 -- may not work on Indigo XS\n') - return f, w, h, pf, colorinfo - -def loadframe(f,w,h,pf,af,spkr, (ybits,ibits,qbits,chrompack),mf): - line = f.readline() - if line == '': - raise EndOfFile - x = eval(line[:-1]) - if type(x) == type(0) or type(x) == type(0.0): - tijd = x - if pf == 0: - size = w*h*4 - else: - size = (w/pf) * (h/pf) - else: - tijd, size = x - data = f.read(size) - if len(data) <> size: - raise EndOfFile - if pf: - w = w/pf - h = h/pf - if chrompack: - cw = (w+chrompack-1)/chrompack - ch = (h+chrompack-1)/chrompack - chromdata = f.read(2*cw*ch) - rectzoom(pf*chrompack*mf,pf*chrompack*mf) - pixmode(PM_SIZE,16) - writemask(0x7ff - ((1< 1: - rectzoom(mf,mf) - lrectwrite(0,0,w-1,h-1,data) - # This is ugly here, but the only way to get the two - # channels started in sync - #if af <> None: - # playsound(af,spkr) - ct = time.millitimer() - epoch.epoch - if epoch.correcttiming and tijd > 0 and ct < tijd: - time.millisleep(tijd-ct) - #swapbuffers() - return tijd - -def initcmap(ybits,ibits,qbits,chrompack): - if ybits+ibits+qbits > 11: - raise 'Sorry, 11 bits max' - maxy = pow(2,ybits) - maxi = pow(2,ibits) - maxq = pow(2,qbits) - for i in range(2048,4096-256): - mapcolor(i, 0, 255, 0) - for y in range(maxy): - yv = float(y)/float(maxy-1) - for i in range(maxi): - if maxi == 1: iv = 0 - else: iv = (float(i)/float(maxi-1))-0.5 - for q in range(maxq): - if maxq == 1: qv = 0 - else: qv = (float(q)/float(maxq-1))-0.5 - index = 2048 + y + (i << ybits) + (q << (ybits+ibits)) - rv,gv,bv = colorsys.yiq_to_rgb(yv,iv,qv) - r,g,b = int(rv*255.0), int(gv*255.0), int(bv*255.0) - if index < 4096 - 256: - mapcolor(index, r,g,b) - -def playsound(af, spkr): - nsamp = spkr.getfillable() - data = af.read(nsamp*2) - spkr.writesamps(data) - -def main(): - looping = 0 - packfactor = 0 - magfactor = 1 - try: - opts, args = getopt.getopt(sys.argv[1:], 'm:p:lF') - except getopt.error: - sys.stderr.write('usage: video ' + \ - '[-l] [-p pf] [-m mag] [-F] [moviefile [soundfile [skipbytes]]]\n') - sys.exit(2) - for opt, arg in opts: - if opt == '-m': - magfactor = int(eval(arg)) - elif opt == '-p': - packfactor = int(eval(arg)) - elif opt == '-l': - looping = 1 - elif opt == '-F': - epoch.correcttiming = 0 - if args: - filename = args[0] - else: - filename = 'film.video' - f, w, h, pf, cinfo = openvideo(filename) - if 0 < packfactor <> pf: - w = w/pf*packfactor - h = h/pf*packfactor - pf = packfactor - if args[1:]: - audiofilename = args[1] - af = open(audiofilename, 'r') - spkr = openspkr() - afskip = 0 - if args[2:]: - afskip = eval(args[2]) - af.seek(afskip) - else: - af, spkr = None, None - foreground() - prefsize(w*magfactor,h*magfactor) - win = winopen(filename) - if pf: - #doublebuffer() - cmode() - else: - RGBmode() - #doublebuffer() - gconfig() - if pf: - initcmap(cinfo) - color(2048) - clear() - writemask(2047) - pixmode(PM_SIZE,8) # 8 bit pixels - qdevice(ESCKEY) - qdevice(WINSHUT) - qdevice(WINQUIT) - running = 1 - epoch.epoch = time.millitimer() - nframe = 0 - tijd = 1 - if looping: - looping = f.tell() - try: - while 1: - if running: - try: - tijd = loadframe(f, w, h, pf, af, spkr, cinfo,magfactor) - nframe = nframe + 1 - except EndOfFile: - running = 0 - t = time.millitimer() - if tijd > 0: - print 'Recorded at', - print 0.1 * int(nframe * 10000.0 / tijd), - print 'frames/sec' - print 'Played', nframe, 'frames at', - print 0.1 * int(nframe * 10000.0 / (t-epoch.epoch)), - print 'frames/sec' - if looping: - f.seek(looping) - epoch.epoch = time.millitimer() - nframe = 0 - running = 1 - if af <> None: - af.seek(afskip) - if af <> None: - playsound(af,spkr) - if not running or qtest(): - dev, val = qread() - if dev in (ESCKEY, WINSHUT, WINQUIT): - raise bye - elif dev == REDRAW: - reshapeviewport() - except bye: - pass - -main() diff --git a/Demo/sgi/video/vinfo.py b/Demo/sgi/video/vinfo.py deleted file mode 100755 index 7f98237a97..0000000000 --- a/Demo/sgi/video/vinfo.py +++ /dev/null @@ -1,90 +0,0 @@ -from gl import * -from GL import * -from DEVICE import * -import time -import sys -import getopt - -class Struct(): pass -epoch = Struct() -EndOfFile = 'End of file' -bye = 'bye' - -def openvideo(filename): - f = open(filename, 'r') - line = f.readline() - if not line: raise EndOfFile - if line[:4] == 'CMIF': line = f.readline() - x = eval(line[:-1]) - if len(x) == 3: w, h, pf = x - else: w, h = x; pf = 2 - return f, w, h, pf - -def loadframe(f, w, h, pf): - line = f.readline() - if line == '': - raise EndOfFile - x = eval(line[:-1]) - if type(x) == type(0) or type(x) == type(0.0): - tijd = x - if pf == 0: - size = w*h*4 - else: - size = (w/pf) * (h/pf) - else: - tijd, size = x - f.seek(size, 1) - return tijd - -def main(): - delta = 0 - short = 0 - try: - opts, names = getopt.getopt(sys.argv[1:], 'ds') - except getopt.error, msg: - sys.stderr.write(msg + '\n') - sys.stderr.write('usage: vinfo [-d] [-s] [file] ...\n') - sys.exit(2) - for opt, arg in opts: - if opt == '-d': delta = 1 # print delta between frames - elif opt == '-s': short = 1 # short: don't print times - if names == []: - names = ['film.video'] - for name in names: - try: - f, w, h, pf = openvideo(name) - except: - sys.stderr.write(name + ': cannot open\n') - continue - if pf == 0: - size = w*h*4 - else: - size = (w/pf) * (h/pf) - print name, ':', w, 'x', h, '; pf =', pf, ', size =', size, - if pf == 0: - print '(color)', - else: - print '(' + `(w/pf)` + 'x' + `(h/pf)` + ')', - if (w/pf)%4 <> 0: print '!!!', - print - num = 0 - try: - otijd = 0 - while not short: - try: - tijd = loadframe(f, w, h, pf) - if delta: print '\t' + `tijd-otijd`, - else: print '\t' + `tijd`, - otijd = tijd - num = num + 1 - if num % 8 == 0: - print - except EndOfFile: - raise bye - except bye: - pass - if num % 8 <> 0: - print - f.close() - -main() diff --git a/Demo/sgi/video/vpregs.py b/Demo/sgi/video/vpregs.py deleted file mode 100755 index d33f1fe93e..0000000000 --- a/Demo/sgi/video/vpregs.py +++ /dev/null @@ -1,28 +0,0 @@ -VID_VP = 0x1000000 - -# Set vp1 register tokens -VP_GBXORG = (VID_VP +0x01) -VP_GBYORG = (VID_VP +0x02) -VP_FBXORG = (VID_VP +0x03) -VP_FBYORG = (VID_VP +0x04) -VP_WIDTH = (VID_VP +0x05) -VP_HEIGHT = (VID_VP +0x06) -VP_PIXCNT = (VID_VP +0x07) -VP_HBLANK = (VID_VP +0x08) -VP_VBLANK = (VID_VP +0x09) -VP_BRITE = (VID_VP +0x0A) -VP_CONT = (VID_VP +0x0B) -VP_HUE = (VID_VP +0x0C) -VP_SAT = (VID_VP +0x0D) -VP_ALPHA = (VID_VP +0X0E) -VP_FGMODE = (VID_VP +0x0F) -VP_MAPSRC = (VID_VP +0x10) -VP_MAPADD = (VID_VP +0x11) -VP_MAPRED = (VID_VP +0x12) -VP_MAPGREEN = (VID_VP +0x13) -VP_MAPBLUE = (VID_VP +0x14) -VP_MAPSTROBE = (VID_VP +0x15) -VP_DIGVAL = (VID_VP +0x16) -VP_STATUS0 = (VID_VP +0x17) -VP_STATUS1 = (VID_VP +0x18) -VP_CMD = (VID_VP +0x19) diff --git a/Demo/sgi/video/vtime.py b/Demo/sgi/video/vtime.py deleted file mode 100755 index c333e57983..0000000000 --- a/Demo/sgi/video/vtime.py +++ /dev/null @@ -1,106 +0,0 @@ -# -# Module vtime - Keep virtual time between two nodes. -# -# We try for synchronised clocks by sending a packet of the for -# (1,mytime,0) to the other side, and waiting (at most) a second for -# a reply. This reply has the form (2,mytime,histime), and we can -# estimate the time difference by defining histime to be exactly half-way -# between the time we sent our message and got our reply. We send a -# final (3,mynewtime,histime) message to allow the other side to do the -# same computations. -# -# Note that the protocol suffers heavily from the 2-army problem. -# It'll have to do until I can read up on time-sync protocols, though. -# -from socket import * -import time - -MSGSIZE = 100 -MSGTIMEOUT = 1000 - -recv_timeout = 'receive timeout' -bad_connect = 'Bad connection' - -def timeavg(a,b): - return int((long(a)+b)/2L) -def tryrecv(s): - cnt = 0 - while 1: - if s.avail(): - return s.recvfrom(MSGSIZE) - time.millisleep(100) - cnt = cnt + 100 - if cnt > MSGTIMEOUT: - raise recv_timeout - -class VTime(): - def init(self,(client,host,port)): - s = socket(AF_INET, SOCK_DGRAM) - host = gethostbyname(host) - localhost = gethostbyname(gethostname()) - raddr = (host,port) - s.bind((localhost,port)) - if client: - # - # We loop here because we want the *second* measurement - # for accuracy - for loopct in (0,2): - curtijd = time.millitimer() - check = `(loopct,curtijd,0)` - s.sendto(check,raddr) - while 1: - try: - if loopct: - data, other = s.recvfrom(MSGSIZE) - else: - data, other = tryrecv(s) - newtijd = time.millitimer() - if other <> raddr: - print 'Someone else syncing to us: ', other - raise bad_connect - data = eval(data) - if data[:2] == (loopct+1,curtijd): - break - if data[0] <> 2: - print 'Illegal sync reply: ', data - raise bad_connect - except recv_timeout: - curtijd = time.millitimer() - check = `(loopct,curtijd,0)` - s.sendto(check,raddr) - histime = data[2] - s.sendto(`(4,newtijd,histime)`,raddr) - mytime = timeavg(curtijd,newtijd) - #mytime = curtijd - self.timediff = histime - mytime - else: - while 1: - data,other = s.recvfrom(MSGSIZE) - if other <> raddr: - print 'Someone else syncing to us: ', other, ' Wanted ', raddr - raise bad_connect - data = eval(data) - if data[0] in (0,2): - curtijd = time.millitimer() - s.sendto(`(data[0]+1,data[1],curtijd)`,raddr) - elif data[0] == 4: - newtijd = time.millitimer() - histime = data[1] - mytime = timeavg(curtijd,newtijd) - #mytime = curtijd - self.timediff = histime-mytime - break - else: - print 'Funny data: ', data - raise bad_connect - return self - # - def his2mine(self,tijd): - return tijd - self.timediff - # - def mine2his(self, tijd): - return tijd + self.timediff - -def test(clt, host, port): - xx = VTime().init(clt,host,port) - print 'Time diff: ', xx.his2mine(0) diff --git a/Demo/sockets/ChangeLog b/Demo/sockets/ChangeLog deleted file mode 100755 index c1d41b1f67..0000000000 --- a/Demo/sockets/ChangeLog +++ /dev/null @@ -1,35 +0,0 @@ -Mon Nov 16 17:55:30 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* Restructured mcast. - -Tue Nov 3 13:08:41 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* Fixed ftp.py to use 'global' instead of a hack - -25-Oct-1992 - -* Added gopher.py - -2-Oct-1992 - -* Changed /usr/local/python to /usr/local/bin/python - -Thu Sep 24 12:33:56 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* Improved computation of mcast group bytes (use regsub.gsub()) - -Tue Sep 8 23:20:51 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* Added mcast.py and IN.py. - -* Use setsockopt() instead of allowbroadcast() in broadcast.py. - -Mon Aug 10 12:45:43 1992 Guido van Rossum (guido@voorn.cwi.nl) - -* README: added broadcast.py, ftp.py, radio.py - -------------------------------------------------------------------------------- -^^^ Log entries after release of 0.9.6 ^^^ -------------------------------------------------------------------------------- - - diff --git a/Demo/tkinter/Tree.py b/Demo/tkinter/Tree.py deleted file mode 100644 index 010fbd4796..0000000000 --- a/Demo/tkinter/Tree.py +++ /dev/null @@ -1,23 +0,0 @@ -from Tkinter import * - -class Tree: - - def __init__(self, master, cnf = {}): - self.master = master - self.outerframe = Frame(self.master, - {'name': 'outerframe', - Pack: {}, - }) - self.innerframe = Frame(self.outerframe, - {'name': 'innerframe', - Pack: {'side': 'left', - 'fill': 'y'}, - }) - self.button = Menubutton(self.innerframe, - {'name': 'button', - Pack: {}, - }) - # menu? - - def addchild(self): - return Tree(self.outerframe, {}) diff --git a/Doc/ACKS b/Doc/ACKS index 8fe9325a2f..5f1efee906 100644 --- a/Doc/ACKS +++ b/Doc/ACKS @@ -19,6 +19,7 @@ Jim Ahlstrom A. Amoroso Pehr Anderson Oliver Andrich +Jesús Cea Avión Daniel Barclay Chris Barker Don Bashford @@ -36,11 +37,13 @@ Gilles Civario Steve Clift Andrew Dalke Ben Darnell +L. Peter Deutsch Robert Donohue Fred L. Drake, Jr. Jeff Epler Michael Ernst Blame Andy Eskilsson +Carey Evans Martijn Faassen Carl Feynman Hernan Martinez Foffani @@ -65,11 +68,13 @@ Stefan Hoffmeister Albert Hofkamp Gregor Hoffleit Steve Holden +Thomas Holenstein Gerrit Holl Rob Hooft Brian Hooper Randall Hopper Michael Hudson +Eric Huss Jeremy Hylton Roger Irwin Jack Jansen @@ -106,6 +111,7 @@ Daniel May Doug Mennella Paolo Milani Skip Montanaro +Paul Moore Ross Moore Sjoerd Mullender Dale Nagata @@ -166,4 +172,5 @@ Steven Work Thomas Wouters Ka-Ping Yee Moshe Zadka +Milan Zamazal Cheng Zhang diff --git a/Doc/Makefile b/Doc/Makefile index 22c88f43b7..5ac103191a 100644 --- a/Doc/Makefile +++ b/Doc/Makefile @@ -67,7 +67,7 @@ TOOLSDIR= tools # This is the *documentation* release, and is used to construct the file # names of the downloadable tarballs. -RELEASE=2.1 +RELEASE=2.1.2 PYTHON= python DVIPS= dvips -N0 -t $(PAPER) diff --git a/Doc/Makefile.deps b/Doc/Makefile.deps index c4107ad100..987beeaa8d 100644 --- a/Doc/Makefile.deps +++ b/Doc/Makefile.deps @@ -5,6 +5,7 @@ COMMONSTYLES= texinputs/python.sty \ texinputs/python.ist COMMONTEX= texinputs/copyright.tex \ + texinputs/license.tex \ texinputs/boilerplate.tex MANSTYLES= texinputs/fncychap.sty \ diff --git a/Doc/README b/Doc/README index 74d32085b8..64fe304f68 100644 --- a/Doc/README +++ b/Doc/README @@ -1,5 +1,5 @@ -Python main documentation -- in LaTeX -------------------------------------- +Python standard documentation -- in LaTeX +----------------------------------------- This directory contains the LaTeX sources to the Python documentation and tools required to support the formatting process. The documents @@ -9,12 +9,13 @@ If you don't have LaTeX, or if you'd rather not format the documentation yourself, you can ftp a tar file containing HTML, PDF, or PostScript versions of all documents. Additional formats may be available. These should be in the same place where you fetched the -main Python distribution (try or -). +main Python distribution (try or +). The following are the LaTeX source files: api/*.tex Python/C API Reference Manual + doc/*.tex Documenting Python ext/*.tex Extending and Embedding the Python Interpreter lib/*.tex Python Library Reference mac/*.tex Macintosh Library Modules @@ -30,15 +31,20 @@ macro definitions useful in documenting Python, and set some style parameters. There's a Makefile to call LaTeX and the other utilities in the right -order and the right number of times. This will produce DVI files for -each document made; to preview them, use xdvi. PostScript is produced -by the same Makefile target that produces the DVI files. This uses -the dvips tool. Printing depends on local conventions; at our site, -we use lpr. For example: +order and the right number of times. By default, it will build the +HTML version of the documnetation, but DVI, PDF, and PostScript can +also be made. To view the generated HTML, point your favorite browser +at the top-level index (html/index.html) after running "make". - make lib # create lib.dvi and lib.ps - xdvi lib # preview lib.dvi - lpr lib.ps # print on default printer +The Makefile can also produce DVI files for each document made; to +preview them, use xdvi. PostScript is produced by the same Makefile +target that produces the DVI files. This uses the dvips tool. +Printing depends on local conventions; at our site, we use lpr. For +example: + + make paper-letter/lib.ps # create lib.dvi and lib.ps + xdvi paper-letter/lib.dvi # preview lib.dvi + lpr paper-letter/lib.ps # print on default printer What if I find a bug? @@ -138,11 +144,12 @@ To create HTML files: - Perl 5.004_04 or newer. Find the software at . - - LaTeX2HTML 99.2b8. Older versions are not supported; each - version changes enough that supporting multiple versions is not - likely to work. Many older versions don't work with Perl - 5.6 as well. This also screws up code fragments. ;-( - Releases are available at: . + - LaTeX2HTML 99.2b8 or newer. Older versions are not + supported; each version changes enough that supporting + multiple versions is not likely to work. Many older + versions don't work with Perl 5.6 as well. This also screws + up code fragments. ;-( Releases are available at: + . What if Times fonts are not available? @@ -161,9 +168,9 @@ style file. What if I want to use A4 paper? ------------------------------- -Instead of building the PostScript by giving the command "make", give -the command "make PAPER=a4 ps"; the output will be produced in the -paper-a4/ subdirectory. (You can use "make PAPER=a4 pdf" if you'd +Instead of building the PostScript by giving the command "make ps", +give the command "make PAPER=a4 ps"; the output will be produced in +the paper-a4/ subdirectory. (You can use "make PAPER=a4 pdf" if you'd rather have PDF output.) @@ -171,8 +178,8 @@ Making HTML files ----------------- The LaTeX documents can be converted to HTML using Nikos Drakos' -LaTeX2HTML converter. See the Makefile; after some twiddling, "make -html" should do the trick. +LaTeX2HTML converter. See the Makefile; after some twiddling, "make" +should do the trick. What else is in here? @@ -194,6 +201,10 @@ manual document class. Create the documentation for a new module by copying the template to lib.tex and editing according to the instructions in the comments. +Documentation on the authoring Python documentation, including +information about both style and markup, is available in the +"Documenting Python" manual. + Copyright notice ================ @@ -202,7 +213,7 @@ The Python source is copyrighted, but you can freely use and copy it as long as you don't change or remove the copyright notice: ---------------------------------------------------------------------- -Copyright (c) 2000, 2001 Guido van Rossum. +Copyright (c) 2000, 2001 Python Software Foundation. All rights reserved. Copyright (c) 2000 BeOpen.com. @@ -214,6 +225,6 @@ All rights reserved. Copyright (c) 1991-1995 Stichting Mathematisch Centrum. All rights reserved. -See the file "LICENSE" for information on usage and +See the file "texinputs/license.tex" for information on usage and redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES. ---------------------------------------------------------------------- diff --git a/Doc/api/api.tex b/Doc/api/api.tex index 58188b5372..e3ba0d2add 100644 --- a/Doc/api/api.tex +++ b/Doc/api/api.tex @@ -55,7 +55,7 @@ Writing an extension module is a relatively well-understood process, where a ``cookbook'' approach works well. There are several tools that automate the process to some extent. While people have embedded Python in other applications since its early existence, the process of -embedding Python is less straightforward that writing an extension. +embedding Python is less straightforward than writing an extension. Many API functions are useful independent of whether you're embedding or extending Python; moreover, most applications that embed Python @@ -107,6 +107,11 @@ multi-platform builds since the platform independent headers under \envvar{prefix} include the platform specific headers from \envvar{exec_prefix}. +\Cpp{} users should note that though the API is defined entirely using +C, the header files do properly declare the entry points to be +\code{extern "C"}, so there is no need to do anything special to use +the API from \Cpp. + \section{Objects, Types and Reference Counts \label{objects}} @@ -305,12 +310,12 @@ The reason is simple: in many cases, the returned object is created on the fly, and the reference you get is the only reference to the object. Therefore, the generic functions that return object references, like \cfunction{PyObject_GetItem()} and -\cfunction{PySequence_GetItem()}, always return a new reference (i.e., -the caller becomes the owner of the reference). +\cfunction{PySequence_GetItem()}, always return a new reference (the +caller becomes the owner of the reference). It is important to realize that whether you own a reference returned by a function depends on which function you call only --- \emph{the -plumage} (i.e., the type of the type of the object passed as an +plumage} (the type of the type of the object passed as an argument to the function) \emph{doesn't enter into it!} Thus, if you extract an item from a list using \cfunction{PyList_GetItem()}, you don't own the reference --- but if you obtain the same item from the @@ -609,6 +614,19 @@ so care should be taken that \ctype{FILE*} parameters are only passed to these functions if it is certain that they were created by the same library that the Python runtime is using. +\begin{cfuncdesc}{int}{Py_Main}{int argc, char **argv} + The main program for the standard interpreter. This is made + available for programs which embed Python. The \var{argc} and + \var{argv} parameters should be prepared exactly as those which are + passed to a C program's \cfunction{main()} function. It is + important to note that the argument list may be modified (but the + contents of the strings pointed to by the argument list are not). + The return value will be the integer passed to the + \function{sys.exit()} function, \code{1} if the interpreter exits + due to an exception, or \code{2} if the parameter list does not + represent a valid Python command line. +\end{cfuncdesc} + \begin{cfuncdesc}{int}{PyRun_AnyFile}{FILE *fp, char *filename} If \var{fp} refers to a file associated with an interactive device (console or terminal input or \UNIX{} pseudo-terminal), return the @@ -862,7 +880,7 @@ and non-\NULL{} value or traceback. The exception type should be a string or class; if it is a class, the value should be an instance of that class. Do not pass an invalid exception type or value. (Violating these rules will cause subtle problems later.) This call -takes away a reference to each object, i.e.\ you must own a reference +takes away a reference to each object: you must own a reference to each object before the call and after the call you no longer own these references. (If you don't understand this, don't use this function. I warned you.) \strong{Note:} This function is normally @@ -938,6 +956,16 @@ returns \NULL{}, so a wrapper function around a system call can write error. \end{cfuncdesc} +\begin{cfuncdesc}{PyObject*}{PyErr_SetFromErrnoWithFilename}{PyObject *type, + char *filename} +Similar to \cfunction{PyErr_SetFromErrno()}, with the additional +behavior that if \var{filename} is not \NULL, it is passed to the +constructor of \var{type} as a third parameter. In the case of +exceptions such as \exception{IOError} and \exception{OSError}, this +is used to define the \member{filename} attribute of the exception +instance. +\end{cfuncdesc} + \begin{cfuncdesc}{void}{PyErr_BadInternalCall}{} This is a shorthand for \samp{PyErr_SetString(PyExc_TypeError, \var{message})}, where \var{message} indicates that an internal @@ -1196,7 +1224,7 @@ by \var{func}. This is a simplified interface to \cfunction{PyImport_ImportModuleEx()} below, leaving the \var{globals} and \var{locals} arguments set to \NULL{}. When the -\var{name} argument contains a dot (i.e., when it specifies a +\var{name} argument contains a dot (when it specifies a submodule of a package), the \var{fromlist} argument is set to the list \code{['*']} so that the return value is the named module rather than the top-level package containing it as would otherwise be the @@ -1742,7 +1770,7 @@ Returns the ``bitwise and'' of \var{o2} and \var{o2} on success and \begin{cfuncdesc}{PyObject*}{PyNumber_Xor}{PyObject *o1, PyObject *o2} Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success, or \NULL{} on failure. This is the equivalent of the Python -expression \samp{\var{o1} \^{ }\var{o2}}. +expression \samp{\var{o1} \textasciicircum{} \var{o2}}. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyNumber_Or}{PyObject *o1, PyObject *o2} @@ -1826,7 +1854,7 @@ and \NULL{} on failure. The operation is done \emph{in-place} when Returns the ``bitwise exclusive or'' of \var{o1} by \var{o2} on success, or \NULL{} on failure. The operation is done \emph{in-place} when \var{o1} supports it. This is the equivalent of the Python expression \samp{\var{o1} -\^= \var{o2}}. +\textasciicircum= \var{o2}}. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyNumber_InPlaceOr}{PyObject *o1, PyObject *o2} @@ -2003,7 +2031,7 @@ raises \exception{TypeError} with \var{m} as the message text. Return the \var{i}th element of \var{o}, assuming that \var{o} was returned by \cfunction{PySequence_Fast()}, and that \var{i} is within bounds. The caller is expected to get the length of the sequence by -calling \cfunction{PyObject_Size()} on \var{o}, since lists and tuples +calling \cfunction{PySequence_Size()} on \var{o}, since lists and tuples are guaranteed to always return their true length. \end{cfuncdesc} @@ -2150,6 +2178,255 @@ no methods. \end{cvardesc} +\section{Numeric Objects \label{numericObjects}} + +\obindex{numeric} + + +\subsection{Plain Integer Objects \label{intObjects}} + +\obindex{integer} +\begin{ctypedesc}{PyIntObject} +This subtype of \ctype{PyObject} represents a Python integer object. +\end{ctypedesc} + +\begin{cvardesc}{PyTypeObject}{PyInt_Type} +This instance of \ctype{PyTypeObject} represents the Python plain +integer type. This is the same object as \code{types.IntType}. +\withsubitem{(in modules types)}{\ttindex{IntType}} +\end{cvardesc} + +\begin{cfuncdesc}{int}{PyInt_Check}{PyObject* o} +Returns true if \var{o} is of type \cdata{PyInt_Type}. +\end{cfuncdesc} + +\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival} +Creates a new integer object with a value of \var{ival}. + +The current implementation keeps an array of integer objects for all +integers between \code{-1} and \code{100}, when you create an int in +that range you actually just get back a reference to the existing +object. So it should be possible to change the value of \code{1}. I +suspect the behaviour of Python in this case is undefined. :-) +\end{cfuncdesc} + +\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io} +Will first attempt to cast the object to a \ctype{PyIntObject}, if +it is not already one, and then return its value. +\end{cfuncdesc} + +\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io} +Returns the value of the object \var{io}. No error checking is +performed. +\end{cfuncdesc} + +\begin{cfuncdesc}{long}{PyInt_GetMax}{} +Returns the system's idea of the largest integer it can handle +(\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system +header files). +\end{cfuncdesc} + + +\subsection{Long Integer Objects \label{longObjects}} + +\obindex{long integer} +\begin{ctypedesc}{PyLongObject} +This subtype of \ctype{PyObject} represents a Python long integer +object. +\end{ctypedesc} + +\begin{cvardesc}{PyTypeObject}{PyLong_Type} +This instance of \ctype{PyTypeObject} represents the Python long +integer type. This is the same object as \code{types.LongType}. +\withsubitem{(in modules types)}{\ttindex{LongType}} +\end{cvardesc} + +\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p} +Returns true if its argument is a \ctype{PyLongObject}. +\end{cfuncdesc} + +\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v} +Returns a new \ctype{PyLongObject} object from \var{v}, or \NULL{} on +failure. +\end{cfuncdesc} + +\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v} +Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned +long}, or \NULL{} on failure. +\end{cfuncdesc} + +\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v} +Returns a new \ctype{PyLongObject} object from the integer part of +\var{v}, or \NULL{} on failure. +\end{cfuncdesc} + +\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong} +Returns a C \ctype{long} representation of the contents of +\var{pylong}. If \var{pylong} is greater than +\constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError} is +raised.\withsubitem{(built-in exception)}{\ttindex{OverflowError}} +\end{cfuncdesc} + +\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong} +Returns a C \ctype{unsigned long} representation of the contents of +\var{pylong}. If \var{pylong} is greater than +\constant{ULONG_MAX}\ttindex{ULONG_MAX}, an \exception{OverflowError} +is raised.\withsubitem{(built-in exception)}{\ttindex{OverflowError}} +\end{cfuncdesc} + +\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong} +Returns a C \ctype{double} representation of the contents of \var{pylong}. +\end{cfuncdesc} + +\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend, + int base} +Return a new \ctype{PyLongObject} based on the string value in +\var{str}, which is interpreted according to the radix in \var{base}. +If \var{pend} is non-\NULL, \code{*\var{pend}} will point to the first +character in \var{str} which follows the representation of the +number. If \var{base} is \code{0}, the radix will be determined base +on the leading characters of \var{str}: if \var{str} starts with +\code{'0x'} or \code{'0X'}, radix 16 will be used; if \var{str} starts +with \code{'0'}, radix 8 will be used; otherwise radix 10 will be +used. If \var{base} is not \code{0}, it must be between \code{2} and +\code{36}, inclusive. Leading spaces are ignored. If there are no +digits, \exception{ValueError} will be raised. +\end{cfuncdesc} + + +\subsection{Floating Point Objects \label{floatObjects}} + +\obindex{floating point} +\begin{ctypedesc}{PyFloatObject} +This subtype of \ctype{PyObject} represents a Python floating point +object. +\end{ctypedesc} + +\begin{cvardesc}{PyTypeObject}{PyFloat_Type} +This instance of \ctype{PyTypeObject} represents the Python floating +point type. This is the same object as \code{types.FloatType}. +\withsubitem{(in modules types)}{\ttindex{FloatType}} +\end{cvardesc} + +\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p} +Returns true if its argument is a \ctype{PyFloatObject}. +\end{cfuncdesc} + +\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v} +Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on +failure. +\end{cfuncdesc} + +\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat} +Returns a C \ctype{double} representation of the contents of \var{pyfloat}. +\end{cfuncdesc} + +\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat} +Returns a C \ctype{double} representation of the contents of +\var{pyfloat}, but without error checking. +\end{cfuncdesc} + + +\subsection{Complex Number Objects \label{complexObjects}} + +\obindex{complex number} +Python's complex number objects are implemented as two distinct types +when viewed from the C API: one is the Python object exposed to +Python programs, and the other is a C structure which represents the +actual complex number value. The API provides functions for working +with both. + +\subsubsection{Complex Numbers as C Structures} + +Note that the functions which accept these structures as parameters +and return them as results do so \emph{by value} rather than +dereferencing them through pointers. This is consistent throughout +the API. + +\begin{ctypedesc}{Py_complex} +The C structure which corresponds to the value portion of a Python +complex number object. Most of the functions for dealing with complex +number objects use structures of this type as input or output values, +as appropriate. It is defined as: + +\begin{verbatim} +typedef struct { + double real; + double imag; +} Py_complex; +\end{verbatim} +\end{ctypedesc} + +\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right} +Return the sum of two complex numbers, using the C +\ctype{Py_complex} representation. +\end{cfuncdesc} + +\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right} +Return the difference between two complex numbers, using the C +\ctype{Py_complex} representation. +\end{cfuncdesc} + +\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex} +Return the negation of the complex number \var{complex}, using the C +\ctype{Py_complex} representation. +\end{cfuncdesc} + +\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right} +Return the product of two complex numbers, using the C +\ctype{Py_complex} representation. +\end{cfuncdesc} + +\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend, + Py_complex divisor} +Return the quotient of two complex numbers, using the C +\ctype{Py_complex} representation. +\end{cfuncdesc} + +\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp} +Return the exponentiation of \var{num} by \var{exp}, using the C +\ctype{Py_complex} representation. +\end{cfuncdesc} + + +\subsubsection{Complex Numbers as Python Objects} + +\begin{ctypedesc}{PyComplexObject} +This subtype of \ctype{PyObject} represents a Python complex number object. +\end{ctypedesc} + +\begin{cvardesc}{PyTypeObject}{PyComplex_Type} +This instance of \ctype{PyTypeObject} represents the Python complex +number type. +\end{cvardesc} + +\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p} +Returns true if its argument is a \ctype{PyComplexObject}. +\end{cfuncdesc} + +\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v} +Create a new Python complex number object from a C +\ctype{Py_complex} value. +\end{cfuncdesc} + +\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag} +Returns a new \ctype{PyComplexObject} object from \var{real} and \var{imag}. +\end{cfuncdesc} + +\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op} +Returns the real part of \var{op} as a C \ctype{double}. +\end{cfuncdesc} + +\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op} +Returns the imaginary part of \var{op} as a C \ctype{double}. +\end{cfuncdesc} + +\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op} +Returns the \ctype{Py_complex} value of the complex number \var{op}. +\end{cfuncdesc} + + + \section{Sequence Objects \label{sequenceObjects}} \obindex{sequence} @@ -2180,7 +2457,8 @@ Returns true if the object \var{o} is a string object. \begin{cfuncdesc}{PyObject*}{PyString_FromString}{const char *v} Returns a new string object with the value \var{v} on success, and -\NULL{} on failure. +\NULL{} on failure. The parameter \var{v} must not be \NULL; it +will not be checked. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyString_FromStringAndSize}{const char *v, @@ -3232,13 +3510,20 @@ Macro form of \cfunction{PyList_GetItem()} without error checking. \begin{cfuncdesc}{int}{PyList_SetItem}{PyObject *list, int index, PyObject *item} Sets the item at index \var{index} in list to \var{item}. -\strong{Note:} This function ``steals'' a reference to \var{item}. +Returns \code{0} on success or \code{-1} on failure. +\strong{Note:} This function ``steals'' a reference to \var{item} and +discards a reference to an item already in the list at the affected +position. \end{cfuncdesc} -\begin{cfuncdesc}{PyObject*}{PyList_SET_ITEM}{PyObject *list, int i, +\begin{cfuncdesc}{void}{PyList_SET_ITEM}{PyObject *list, int i, PyObject *o} Macro form of \cfunction{PyList_SetItem()} without error checking. -\strong{Note:} This function ``steals'' a reference to \var{item}. +\strong{Note:} This function ``steals'' a reference to \var{item}, +and, unlike \cfunction{PyList_SetItem()}, does \emph{not} discard a +reference to any item that it being replaced; any reference in +\var{list} at position \var{i} will be leaked. This is normally only +used to fill in new lists where there is no previous content. \end{cfuncdesc} \begin{cfuncdesc}{int}{PyList_Insert}{PyObject *list, int index, @@ -3328,17 +3613,19 @@ Empties an existing dictionary of all key-value pairs. \begin{cfuncdesc}{int}{PyDict_SetItem}{PyObject *p, PyObject *key, PyObject *val} -Inserts \var{value} into the dictionary with a key of \var{key}. +Inserts \var{value} into the dictionary \var{p} with a key of \var{key}. \var{key} must be hashable; if it isn't, \exception{TypeError} will be raised. +Returns \code{0} on success or \code{-1} on failure. \end{cfuncdesc} \begin{cfuncdesc}{int}{PyDict_SetItemString}{PyObject *p, char *key, PyObject *val} -Inserts \var{value} into the dictionary using \var{key} +Inserts \var{value} into the dictionary \var{p} using \var{key} as a key. \var{key} should be a \ctype{char*}. The key object is created using \code{PyString_FromString(\var{key})}. +Returns \code{0} on success or \code{-1} on failure. \ttindex{PyString_FromString()} \end{cfuncdesc} @@ -3351,6 +3638,7 @@ raised. \begin{cfuncdesc}{int}{PyDict_DelItemString}{PyObject *p, char *key} Removes the entry in dictionary \var{p} which has a key specified by the string \var{key}. +Returns \code{0} on success or \code{-1} on failure. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyDict_GetItem}{PyObject *p, PyObject *key} @@ -3434,255 +3722,6 @@ while (PyDict_Next(self->dict, &pos, &key, &value)) { \end{cfuncdesc} -\section{Numeric Objects \label{numericObjects}} - -\obindex{numeric} - - -\subsection{Plain Integer Objects \label{intObjects}} - -\obindex{integer} -\begin{ctypedesc}{PyIntObject} -This subtype of \ctype{PyObject} represents a Python integer object. -\end{ctypedesc} - -\begin{cvardesc}{PyTypeObject}{PyInt_Type} -This instance of \ctype{PyTypeObject} represents the Python plain -integer type. This is the same object as \code{types.IntType}. -\withsubitem{(in modules types)}{\ttindex{IntType}} -\end{cvardesc} - -\begin{cfuncdesc}{int}{PyInt_Check}{PyObject* o} -Returns true if \var{o} is of type \cdata{PyInt_Type}. -\end{cfuncdesc} - -\begin{cfuncdesc}{PyObject*}{PyInt_FromLong}{long ival} -Creates a new integer object with a value of \var{ival}. - -The current implementation keeps an array of integer objects for all -integers between \code{-1} and \code{100}, when you create an int in -that range you actually just get back a reference to the existing -object. So it should be possible to change the value of \code{1}. I -suspect the behaviour of Python in this case is undefined. :-) -\end{cfuncdesc} - -\begin{cfuncdesc}{long}{PyInt_AsLong}{PyObject *io} -Will first attempt to cast the object to a \ctype{PyIntObject}, if -it is not already one, and then return its value. -\end{cfuncdesc} - -\begin{cfuncdesc}{long}{PyInt_AS_LONG}{PyObject *io} -Returns the value of the object \var{io}. No error checking is -performed. -\end{cfuncdesc} - -\begin{cfuncdesc}{long}{PyInt_GetMax}{} -Returns the system's idea of the largest integer it can handle -(\constant{LONG_MAX}\ttindex{LONG_MAX}, as defined in the system -header files). -\end{cfuncdesc} - - -\subsection{Long Integer Objects \label{longObjects}} - -\obindex{long integer} -\begin{ctypedesc}{PyLongObject} -This subtype of \ctype{PyObject} represents a Python long integer -object. -\end{ctypedesc} - -\begin{cvardesc}{PyTypeObject}{PyLong_Type} -This instance of \ctype{PyTypeObject} represents the Python long -integer type. This is the same object as \code{types.LongType}. -\withsubitem{(in modules types)}{\ttindex{LongType}} -\end{cvardesc} - -\begin{cfuncdesc}{int}{PyLong_Check}{PyObject *p} -Returns true if its argument is a \ctype{PyLongObject}. -\end{cfuncdesc} - -\begin{cfuncdesc}{PyObject*}{PyLong_FromLong}{long v} -Returns a new \ctype{PyLongObject} object from \var{v}, or \NULL{} on -failure. -\end{cfuncdesc} - -\begin{cfuncdesc}{PyObject*}{PyLong_FromUnsignedLong}{unsigned long v} -Returns a new \ctype{PyLongObject} object from a C \ctype{unsigned -long}, or \NULL{} on failure. -\end{cfuncdesc} - -\begin{cfuncdesc}{PyObject*}{PyLong_FromDouble}{double v} -Returns a new \ctype{PyLongObject} object from the integer part of -\var{v}, or \NULL{} on failure. -\end{cfuncdesc} - -\begin{cfuncdesc}{long}{PyLong_AsLong}{PyObject *pylong} -Returns a C \ctype{long} representation of the contents of -\var{pylong}. If \var{pylong} is greater than -\constant{LONG_MAX}\ttindex{LONG_MAX}, an \exception{OverflowError} is -raised.\withsubitem{(built-in exception)}{OverflowError} -\end{cfuncdesc} - -\begin{cfuncdesc}{unsigned long}{PyLong_AsUnsignedLong}{PyObject *pylong} -Returns a C \ctype{unsigned long} representation of the contents of -\var{pylong}. If \var{pylong} is greater than -\constant{ULONG_MAX}\ttindex{ULONG_MAX}, an \exception{OverflowError} -is raised.\withsubitem{(built-in exception)}{OverflowError} -\end{cfuncdesc} - -\begin{cfuncdesc}{double}{PyLong_AsDouble}{PyObject *pylong} -Returns a C \ctype{double} representation of the contents of \var{pylong}. -\end{cfuncdesc} - -\begin{cfuncdesc}{PyObject*}{PyLong_FromString}{char *str, char **pend, - int base} -Return a new \ctype{PyLongObject} based on the string value in -\var{str}, which is interpreted according to the radix in \var{base}. -If \var{pend} is non-\NULL, \code{*\var{pend}} will point to the first -character in \var{str} which follows the representation of the -number. If \var{base} is \code{0}, the radix will be determined base -on the leading characters of \var{str}: if \var{str} starts with -\code{'0x'} or \code{'0X'}, radix 16 will be used; if \var{str} starts -with \code{'0'}, radix 8 will be used; otherwise radix 10 will be -used. If \var{base} is not \code{0}, it must be between \code{2} and -\code{36}, inclusive. Leading spaces are ignored. If there are no -digits, \exception{ValueError} will be raised. -\end{cfuncdesc} - - -\subsection{Floating Point Objects \label{floatObjects}} - -\obindex{floating point} -\begin{ctypedesc}{PyFloatObject} -This subtype of \ctype{PyObject} represents a Python floating point -object. -\end{ctypedesc} - -\begin{cvardesc}{PyTypeObject}{PyFloat_Type} -This instance of \ctype{PyTypeObject} represents the Python floating -point type. This is the same object as \code{types.FloatType}. -\withsubitem{(in modules types)}{\ttindex{FloatType}} -\end{cvardesc} - -\begin{cfuncdesc}{int}{PyFloat_Check}{PyObject *p} -Returns true if its argument is a \ctype{PyFloatObject}. -\end{cfuncdesc} - -\begin{cfuncdesc}{PyObject*}{PyFloat_FromDouble}{double v} -Creates a \ctype{PyFloatObject} object from \var{v}, or \NULL{} on -failure. -\end{cfuncdesc} - -\begin{cfuncdesc}{double}{PyFloat_AsDouble}{PyObject *pyfloat} -Returns a C \ctype{double} representation of the contents of \var{pyfloat}. -\end{cfuncdesc} - -\begin{cfuncdesc}{double}{PyFloat_AS_DOUBLE}{PyObject *pyfloat} -Returns a C \ctype{double} representation of the contents of -\var{pyfloat}, but without error checking. -\end{cfuncdesc} - - -\subsection{Complex Number Objects \label{complexObjects}} - -\obindex{complex number} -Python's complex number objects are implemented as two distinct types -when viewed from the C API: one is the Python object exposed to -Python programs, and the other is a C structure which represents the -actual complex number value. The API provides functions for working -with both. - -\subsubsection{Complex Numbers as C Structures} - -Note that the functions which accept these structures as parameters -and return them as results do so \emph{by value} rather than -dereferencing them through pointers. This is consistent throughout -the API. - -\begin{ctypedesc}{Py_complex} -The C structure which corresponds to the value portion of a Python -complex number object. Most of the functions for dealing with complex -number objects use structures of this type as input or output values, -as appropriate. It is defined as: - -\begin{verbatim} -typedef struct { - double real; - double imag; -} Py_complex; -\end{verbatim} -\end{ctypedesc} - -\begin{cfuncdesc}{Py_complex}{_Py_c_sum}{Py_complex left, Py_complex right} -Return the sum of two complex numbers, using the C -\ctype{Py_complex} representation. -\end{cfuncdesc} - -\begin{cfuncdesc}{Py_complex}{_Py_c_diff}{Py_complex left, Py_complex right} -Return the difference between two complex numbers, using the C -\ctype{Py_complex} representation. -\end{cfuncdesc} - -\begin{cfuncdesc}{Py_complex}{_Py_c_neg}{Py_complex complex} -Return the negation of the complex number \var{complex}, using the C -\ctype{Py_complex} representation. -\end{cfuncdesc} - -\begin{cfuncdesc}{Py_complex}{_Py_c_prod}{Py_complex left, Py_complex right} -Return the product of two complex numbers, using the C -\ctype{Py_complex} representation. -\end{cfuncdesc} - -\begin{cfuncdesc}{Py_complex}{_Py_c_quot}{Py_complex dividend, - Py_complex divisor} -Return the quotient of two complex numbers, using the C -\ctype{Py_complex} representation. -\end{cfuncdesc} - -\begin{cfuncdesc}{Py_complex}{_Py_c_pow}{Py_complex num, Py_complex exp} -Return the exponentiation of \var{num} by \var{exp}, using the C -\ctype{Py_complex} representation. -\end{cfuncdesc} - - -\subsubsection{Complex Numbers as Python Objects} - -\begin{ctypedesc}{PyComplexObject} -This subtype of \ctype{PyObject} represents a Python complex number object. -\end{ctypedesc} - -\begin{cvardesc}{PyTypeObject}{PyComplex_Type} -This instance of \ctype{PyTypeObject} represents the Python complex -number type. -\end{cvardesc} - -\begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p} -Returns true if its argument is a \ctype{PyComplexObject}. -\end{cfuncdesc} - -\begin{cfuncdesc}{PyObject*}{PyComplex_FromCComplex}{Py_complex v} -Create a new Python complex number object from a C -\ctype{Py_complex} value. -\end{cfuncdesc} - -\begin{cfuncdesc}{PyObject*}{PyComplex_FromDoubles}{double real, double imag} -Returns a new \ctype{PyComplexObject} object from \var{real} and \var{imag}. -\end{cfuncdesc} - -\begin{cfuncdesc}{double}{PyComplex_RealAsDouble}{PyObject *op} -Returns the real part of \var{op} as a C \ctype{double}. -\end{cfuncdesc} - -\begin{cfuncdesc}{double}{PyComplex_ImagAsDouble}{PyObject *op} -Returns the imaginary part of \var{op} as a C \ctype{double}. -\end{cfuncdesc} - -\begin{cfuncdesc}{Py_complex}{PyComplex_AsCComplex}{PyObject *op} -Returns the \ctype{Py_complex} value of the complex number \var{op}. -\end{cfuncdesc} - - - \section{Other Objects \label{otherObjects}} \subsection{File Objects \label{fileObjects}} @@ -4511,15 +4550,15 @@ discussion of this macro. It is a no-op when thread support is disabled at compile time. \end{csimplemacrodesc} -\begin{csimplemacrodesc}{Py_BEGIN_BLOCK_THREADS} -This macro expands to \samp{PyEval_RestoreThread(_save);} i.e. it +\begin{csimplemacrodesc}{Py_BLOCK_THREADS} +This macro expands to \samp{PyEval_RestoreThread(_save);}: it is equivalent to \code{Py_END_ALLOW_THREADS} without the closing brace. It is a no-op when thread support is disabled at compile time. \end{csimplemacrodesc} -\begin{csimplemacrodesc}{Py_BEGIN_UNBLOCK_THREADS} -This macro expands to \samp{_save = PyEval_SaveThread();} i.e. it is +\begin{csimplemacrodesc}{Py_UNBLOCK_THREADS} +This macro expands to \samp{_save = PyEval_SaveThread();}: it is equivalent to \code{Py_BEGIN_ALLOW_THREADS} without the opening brace and variable declaration. It is a no-op when thread support is disabled at compile time. @@ -4575,6 +4614,14 @@ argument \var{tstate}, which may be \NULL{}. The interpreter lock must be held. \end{cfuncdesc} +\begin{cfuncdesc}{PyObject*}{PyThreadState_GetDict}{} +Return a dictionary in which extensions can store thread-specific +state information. Each extension should use a unique key to use to +store state in the dictionary. If this function returns \NULL, an +exception has been raised and the caller should allow it to +propogate. +\end{cfuncdesc} + \chapter{Memory Management \label{memory}} \sectionauthor{Vladimir Marangozov}{Vladimir.Marangozov@inrialpes.fr} @@ -4663,18 +4710,20 @@ available for allocating and releasing memory from the Python heap: \begin{cfuncdesc}{void*}{PyMem_Malloc}{size_t n} Allocates \var{n} bytes and returns a pointer of type \ctype{void*} to -the allocated memory, or \NULL{} if the request fails. Requesting zero +the allocated memory, or \NULL{} if the request fails. Requesting zero bytes returns a non-\NULL{} pointer. +The memory will not have been initialized in any way. \end{cfuncdesc} \begin{cfuncdesc}{void*}{PyMem_Realloc}{void *p, size_t n} Resizes the memory block pointed to by \var{p} to \var{n} bytes. The contents will be unchanged to the minimum of the old and the new sizes. If \var{p} is \NULL{}, the call is equivalent to -\cfunction{PyMem_Malloc(\var{n})}; if \var{n} is equal to zero, the memory block -is resized but is not freed, and the returned pointer is non-\NULL{}. -Unless \var{p} is \NULL{}, it must have been returned by a previous -call to \cfunction{PyMem_Malloc()} or \cfunction{PyMem_Realloc()}. +\cfunction{PyMem_Malloc(\var{n})}; if \var{n} is equal to zero, the +memory block is resized but is not freed, and the returned pointer is +non-\NULL{}. Unless \var{p} is \NULL{}, it must have been returned by +a previous call to \cfunction{PyMem_Malloc()} or +\cfunction{PyMem_Realloc()}. \end{cfuncdesc} \begin{cfuncdesc}{void}{PyMem_Free}{void *p} @@ -4692,6 +4741,7 @@ that \var{TYPE} refers to any C type. Same as \cfunction{PyMem_Malloc()}, but allocates \code{(\var{n} * sizeof(\var{TYPE}))} bytes of memory. Returns a pointer cast to \ctype{\var{TYPE}*}. +The memory will not have been initialized in any way. \end{cfuncdesc} \begin{cfuncdesc}{\var{TYPE}*}{PyMem_Resize}{void *p, TYPE, size_t n} @@ -4788,31 +4838,65 @@ implementing new object types in C. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{PyObject_Init}{PyObject *op, - PyTypeObject *type} + PyTypeObject *type} + Initialize a newly-allocated object \var{op} with its type and + initial reference. Returns the initialized object. If \var{type} + indicates that the object participates in the cyclic garbage + detector, it it added to the detector's set of observed objects. + Other fields of the object are not affected. \end{cfuncdesc} \begin{cfuncdesc}{PyVarObject*}{PyObject_InitVar}{PyVarObject *op, - PyTypeObject *type, int size} + PyTypeObject *type, int size} + This does everything \cfunction{PyObject_Init()} does, and also + initializes the length information for a variable-size object. \end{cfuncdesc} \begin{cfuncdesc}{\var{TYPE}*}{PyObject_New}{TYPE, PyTypeObject *type} + Allocate a new Python object using the C structure type \var{TYPE} + and the Python type object \var{type}. Fields not defined by the + Python object header are not initialized; the object's reference + count will be one. The size of the memory + allocation is determined from the \member{tp_basicsize} field of the + type object. \end{cfuncdesc} \begin{cfuncdesc}{\var{TYPE}*}{PyObject_NewVar}{TYPE, PyTypeObject *type, int size} + Allocate a new Python object using the C structure type \var{TYPE} + and the Python type object \var{type}. Fields not defined by the + Python object header are not initialized. The allocated memory + allows for the \var{TYPE} structure plus \var{size} fields of the + size given by the \member{tp_itemsize} field of \var{type}. This is + useful for implementing objects like tuples, which are able to + determine their size at construction time. Embedding the array of + fields into the same allocation decreases the number of allocations, + improving the memory management efficiency. \end{cfuncdesc} \begin{cfuncdesc}{void}{PyObject_Del}{PyObject *op} + Releases memory allocated to an object using + \cfunction{PyObject_New()} or \cfunction{PyObject_NewVar()}. This + is normally called from the \member{tp_dealloc} handler specified in + the object's type. The fields of the object should not be accessed + after this call as the memory is no longer a valid Python object. \end{cfuncdesc} \begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW}{TYPE, PyTypeObject *type} + Macro version of \cfunction{PyObject_New()}, to gain performance at + the expense of safety. This does not check \var{type} for a \NULL{} + value. \end{cfuncdesc} \begin{cfuncdesc}{\var{TYPE}*}{PyObject_NEW_VAR}{TYPE, PyTypeObject *type, int size} + Macro version of \cfunction{PyObject_NewVar()}, to gain performance + at the expense of safety. This does not check \var{type} for a + \NULL{} value. \end{cfuncdesc} \begin{cfuncdesc}{void}{PyObject_DEL}{PyObject *op} + Macro version of \cfunction{PyObject_Del()}. \end{cfuncdesc} \begin{cfuncdesc}{PyObject*}{Py_InitModule}{char *name, @@ -4847,13 +4931,39 @@ implementing new object types in C. sure you need it. \end{cfuncdesc} -PyArg_ParseTupleAndKeywords, PyArg_ParseTuple, PyArg_Parse +\begin{cfuncdesc}{int}{PyArg_ParseTuple}{PyObject *args, char *format, + \moreargs} + Parse the parameters of a function that takes only positional + parameters into local variables. See + \citetitle[../ext/parseTuple.html]{Extending and Embedding the + Python Interpreter} for more information. +\end{cfuncdesc} + +\begin{cfuncdesc}{int}{PyArg_ParseTupleAndKeywords}{PyObject *args, + PyObject *kw, char *format, char *keywords[], \moreargs} + Parse the parameters of a function that takes both positional and + keyword parameters into local variables. See + \citetitle[../ext/parseTupleAndKeywords.html]{Extending and + Embedding the Python Interpreter} for more information. +\end{cfuncdesc} + +\begin{cfuncdesc}{int}{PyArg_Parse}{PyObject *args, char *format, \moreargs} + Function used to deconstruct the argument lists of ``old-style'' + functions --- these are functions which use the + \constant{METH_OLDARGS} parameter parsing method. This is not + recommended for new code, and most code in the standard interpreter + has been modified to no longer use this. +\end{cfuncdesc} Py_BuildValue DL_IMPORT -_Py_NoneStruct +\begin{cvardesc}{PyObject}{_Py_NoneStruct} + Object which is visible in Python as \code{None}. This should only + be accessed using the \code{Py_None} macro, which evaluates to a + pointer to this object. +\end{cvardesc} \section{Common Object Structures \label{common-structs}} @@ -5128,7 +5238,7 @@ The \member{tp_clear} handler must be of the \ctype{inquiry} type, or Drop references that may have created reference cycles. Immutable objects do not have to define this method since they can never directly create reference cycles. Note that the object must still - be valid after calling this method (i.e., don't just call + be valid after calling this method (don't just call \cfunction{Py_DECREF()} on a reference). The collector will call this method if it detects that this object is involved in a reference cycle. @@ -5244,6 +5354,9 @@ new_object(PyObject *unused, PyObject *args) \chapter{Reporting Bugs} \input{reportingbugs} +\chapter{History and License} +\input{license} + \input{api.ind} % Index -- must be last \end{document} diff --git a/Doc/api/refcounts.dat b/Doc/api/refcounts.dat index 2a3cc00e38..f69b4f6ddd 100644 --- a/Doc/api/refcounts.dat +++ b/Doc/api/refcounts.dat @@ -400,7 +400,7 @@ PyList_New:int:len:: PyList_Reverse:int::: PyList_Reverse:PyObject*:list:0: -PyList_SET_ITEM:PyObject*::0: +PyList_SET_ITEM:void::: PyList_SET_ITEM:PyObject*:list:0: PyList_SET_ITEM:int:i:: PyList_SET_ITEM:PyObject*:o:0: diff --git a/Doc/doc/doc.tex b/Doc/doc/doc.tex index 215e37013d..a86c45079d 100644 --- a/Doc/doc/doc.tex +++ b/Doc/doc/doc.tex @@ -192,12 +192,14 @@ distribution, to create or maintain whole documents or sections. The document body follows the preamble. This contains all the printed components of the document marked up structurally. Generic - \LaTeX{} structures include hierarchical sections + \LaTeX{} structures include hierarchical sections, numbered and + bulleted lists, and special structures for the document abstract and + indexes. \subsection{Syntax} - There are a things that an author of Python documentation needs to - know about \LaTeX{} syntax. + There are some things that an author of Python documentation needs + to know about \LaTeX{} syntax. A \dfn{comment} is started by the ``percent'' character (\character{\%}) and continues through the end of the line and all @@ -235,7 +237,7 @@ Still more text. {text in a group} \end{verbatim} - An alternate syntax for a group using brackets (\code{[...]}) is + An alternate syntax for a group using brackets, \code{[...]}, is used by macros and environment constructors which take optional parameters; brackets do not normally hold syntactic significance. A degenerate group, containing only one atomic bit of content, @@ -246,7 +248,7 @@ Still more text. Groups are used only sparingly in the Python documentation, except for their use in marking parameters to macros and environments. - A \dfn{macro} is usually simple construct which is identified by + A \dfn{macro} is usually a simple construct which is identified by name and can take some number of parameters. In normal \LaTeX{} usage, one of these can be optional. The markup is introduced using the backslash character (\character{\e}), and the name is @@ -279,14 +281,14 @@ Still more text. A macro name may be followed by a space or newline; a space between the macro name and any parameters will be consumed, but this usage is not practiced in the Python documentation. Such a - space is still consumed if there are no parameters to the marco, + space is still consumed if there are no parameters to the macro, in which case inserting an empty group (\code{\{\}}) or explicit word space (\samp{\e\ }) immediately after the macro name helps to avoid running the expansion of the macro into the following text. Macros which take no parameters but which should not be followed by a word space do not need special treatment if the following character in the document source if not a name character (such as - puctuation). + punctuation). Each line of this example shows an appropriate way to write text which includes a macro which takes no parameters: @@ -298,12 +300,12 @@ This \UNIX\ is also followed by a space. \end{verbatim} An \dfn{environment} is a larger construct than a macro, and can - be used for things with more content that would conveniently fit + be used for things with more content than would conveniently fit in a macro parameter. They are primarily used when formatting parameters need to be changed before and after a large chunk of content, but the content itself needs to be highly flexible. Code samples are presented using an environment, and descriptions of - functions, methods, and classes are also marked using envionments. + functions, methods, and classes are also marked using environments. Since the content of an environment is free-form and can consist of several paragraphs, they are actually marked using a pair of @@ -333,11 +335,11 @@ This \UNIX\ is also followed by a space. \end{datadesc} \end{verbatim} - There are a number of less-used marks in \LaTeX{} are used to - enter non-\ASCII{} characters, especially those used in European - names. Given that these are often used adjacent to other + There are a number of less-used marks in \LaTeX{} which are used + to enter non-\ASCII{} characters, especially those used in + European names. Given that these are often used adjacent to other characters, the markup required to produce the proper character - may need to be followed by a space or an empty group, or the the + may need to be followed by a space or an empty group, or the markup can be enclosed in a group. Some which are found in Python documentation are: @@ -357,8 +359,9 @@ This \UNIX\ is also followed by a space. safely inferred when a section of equal or higher level starts. There are six ``levels'' of sectioning in the document classes - used for Python documentation, and the lowest two levels are not - used. The levels are: + used for Python documentation, and the deepest two + levels\footnote{The deepest levels have the highest numbers in the + table.} are not used. The levels are: \begin{tableiii}{c|l|c}{textrm}{Level}{Macro Name}{Notes} \lineiii{1}{\macro{chapter}}{(1)} @@ -837,12 +840,15 @@ This \UNIX\ is also followed by a space. \macro{shortversion} macro. \end{macrodesc} - \begin{macrodesc}{versionadded}{\p{version}} + \begin{macrodesc}{versionadded}{\op{explanation}\p{version}} The version of Python which added the described feature to the - library or C API. This is typically added to the end of the - first paragraph of the description before any availability - notes. The location should be selected so the explanation makes - sense and may vary as needed. + library or C API. \var{explanation} should be a \emph{brief} + explanation of the change consisting of a capitalized sentence + fragment; a period will be appended by the formatting process. + This is typically added to the end of the first paragraph of the + description before any availability notes. The location should + be selected so the explanation makes sense and may vary as + needed. \end{macrodesc} \begin{macrodesc}{versionchanged}{\op{explanation}\p{version}} diff --git a/Doc/ext/ext.tex b/Doc/ext/ext.tex index 446802fd22..bbe7efaf9b 100644 --- a/Doc/ext/ext.tex +++ b/Doc/ext/ext.tex @@ -2578,4 +2578,7 @@ corresponds to the variable of the same name in Python's top-level \chapter{Reporting Bugs} \input{reportingbugs} +\chapter{History and License} +\input{license} + \end{document} diff --git a/Doc/lib/libanydbm.tex b/Doc/lib/libanydbm.tex index 367daf6ed9..2718936fea 100644 --- a/Doc/lib/libanydbm.tex +++ b/Doc/lib/libanydbm.tex @@ -72,17 +72,13 @@ should only be used when no other DBM-style database is available. \begin{funcdesc}{open}{filename\optional{, flag\optional{, mode}}} -Open the database file \var{filename} and return a corresponding object. -The optional \var{flag} argument can be -\code{'r'} to open an existing database for reading only, -\code{'w'} to open an existing database for reading and writing, -\code{'c'} to create the database if it doesn't exist, or -\code{'n'}, which will always create a new empty database. If not -specified, the default value is \code{'r'}. +Open the database file \var{filename} and return a corresponding +object. The \var{flag} argument, used to control how the database is +opened in the other DBM implementations, is ignored in +\module{dumbdbm}; the database is always opened for update, and will +be created if it does not exist. -The optional \var{mode} argument is the \UNIX{} mode of the file, used -only when the database has to be created. It defaults to octal -\code{0666} (and will be modified by the prevailing umask). +The optional \var{mode} argument is ignored. \end{funcdesc} \begin{excdesc}{error} diff --git a/Doc/lib/libascii.tex b/Doc/lib/libascii.tex index ae4fe6f61b..003bd9544d 100644 --- a/Doc/lib/libascii.tex +++ b/Doc/lib/libascii.tex @@ -3,7 +3,7 @@ \declaremodule{standard}{curses.ascii} \modulesynopsis{Constants and set-membership functions for - \ASCII{} characters.} + \ASCII\ characters.} \moduleauthor{Eric S. Raymond}{esr@thyrsus.com} \sectionauthor{Eric S. Raymond}{esr@thyrsus.com} diff --git a/Doc/lib/libasyncore.tex b/Doc/lib/libasyncore.tex index cce0d50ebe..66998d11e8 100644 --- a/Doc/lib/libasyncore.tex +++ b/Doc/lib/libasyncore.tex @@ -136,7 +136,7 @@ identical to their socket partners. Read at most \var{buffer_size} bytes from the socket. \end{methoddesc} -\begin{methoddesc}{listen}{\optional{backlog}} +\begin{methoddesc}{listen}{backlog} Listen for connections made to the socket. The \var{backlog} argument specifies the maximum number of queued connections and should be at least 1; the maximum value is diff --git a/Doc/lib/libbinascii.tex b/Doc/lib/libbinascii.tex index 55a743ab31..a569a47d32 100644 --- a/Doc/lib/libbinascii.tex +++ b/Doc/lib/libbinascii.tex @@ -3,7 +3,7 @@ \declaremodule{builtin}{binascii} \modulesynopsis{Tools for converting between binary and various - \ASCII{}-encoded binary representations.} + \ASCII-encoded binary representations.} The \module{binascii} module contains a number of methods to convert diff --git a/Doc/lib/libcalendar.tex b/Doc/lib/libcalendar.tex index f5dd8c412a..c6ca67fee3 100644 --- a/Doc/lib/libcalendar.tex +++ b/Doc/lib/libcalendar.tex @@ -3,7 +3,7 @@ \declaremodule{standard}{calendar} \modulesynopsis{General functions for working with the calendar, - including some emulation of the \UNIX{} \program{cal} + including some emulation of the \UNIX\ \program{cal} program.} \sectionauthor{Drew Csillag}{drew_csillag@geocities.com} diff --git a/Doc/lib/libcfgparser.tex b/Doc/lib/libcfgparser.tex index 65c27ce203..54b4d0d480 100644 --- a/Doc/lib/libcfgparser.tex +++ b/Doc/lib/libcfgparser.tex @@ -134,6 +134,24 @@ otherwise return 0. (New in 1.6) \begin{methoddesc}{read}{filenames} Read and parse a list of filenames. If \var{filenames} is a string or Unicode string, it is treated as a single filename. +If a file named in \var{filenames} cannot be opened, that file will be +ignored. This is designed so that you can specify a list of potential +configuration file locations (for example, the current directory, the +user's home directory, and some system-wide directory), and all +existing configuration files in the list will be read. If none of the +named files exist, the \class{ConfigParser} instance will contain an +empty dataset. An application which requires initial values to be +loaded from a file should load the required file or files using +\method{readfp()} before calling \method{read()} for any optional +files: + +\begin{verbatim} +import ConfigParser, os + +config = ConfigParser.ConfigParser() +config.readfp(open('defaults.cfg')) +config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')]) +\end{verbatim} \end{methoddesc} \begin{methoddesc}{readfp}{fp\optional{, filename}} diff --git a/Doc/lib/libcgi.tex b/Doc/lib/libcgi.tex index 285c08f66e..8ab562d8b2 100644 --- a/Doc/lib/libcgi.tex +++ b/Doc/lib/libcgi.tex @@ -89,10 +89,7 @@ non-empty string: \begin{verbatim} form = cgi.FieldStorage() -form_ok = 0 -if form.has_key("name") and form.has_key("addr"): - form_ok = 1 -if not form_ok: +if not (form.has_key("name") and form.has_key("addr")): print "

Error

" print "Please fill in the name and addr fields." return diff --git a/Doc/lib/libcgihttp.tex b/Doc/lib/libcgihttp.tex index 61cd08c334..f9a0b504ec 100644 --- a/Doc/lib/libcgihttp.tex +++ b/Doc/lib/libcgihttp.tex @@ -3,7 +3,6 @@ \declaremodule{standard}{CGIHTTPServer} - \platform{Unix} \sectionauthor{Moshe Zadka}{moshez@zadka.site.co.il} \modulesynopsis{This module provides a request handler for HTTP servers which can run CGI scripts.} @@ -15,8 +14,9 @@ interface compatible with from \class{SimpleHTTPServer.SimpleHTTPRequestHandler} but can also run CGI scripts. -\strong{Note:} This module is \UNIX{} dependent since it creates the -CGI process using \function{os.fork()} and \function{os.exec()}. +\strong{Note:} This module can run CGI scripts on \UNIX{} and Windows +systems; on Mac OS it will only be able to run Python scripts within +the same process as itself. The \module{CGIHTTPServer} module defines the following class: diff --git a/Doc/lib/libcmd.tex b/Doc/lib/libcmd.tex index e38fc241c7..f24add37f4 100644 --- a/Doc/lib/libcmd.tex +++ b/Doc/lib/libcmd.tex @@ -56,8 +56,11 @@ any undocumented commands. \end{methoddesc} \begin{methoddesc}{onecmd}{str} -Interpret the argument as though it had been typed in in -response to the prompt. +Interpret the argument as though it had been typed in response to the +prompt. This may be overridden, but should not normally need to be; +see the \method{precmd()} and \method{postcmd()} methods for useful +execution hooks. The return value is a flag indicating whether +interpretation of commands by the interpreter should stop. \end{methoddesc} \begin{methoddesc}{emptyline}{} @@ -73,15 +76,25 @@ error message and returns. \end{methoddesc} \begin{methoddesc}{precmd}{} -Hook method executed just before the input prompt is issued. This +Hook method executed just before the command line \var{line} is +interpreted, but after the input prompt is generated and issued. This method is a stub in \class{Cmd}; it exists to be overridden by -subclasses. +subclasses. The return value is used as the command which will be +executed by the \method{onecmd()} method; the \method{precmd()} +implementation may re-write the command or simply return \var{line} +unchanged. \end{methoddesc} -\begin{methoddesc}{postcmd}{} +\begin{methoddesc}{postcmd}{stop, line} Hook method executed just after a command dispatch is finished. This method is a stub in \class{Cmd}; it exists to be overridden by -subclasses. +subclasses. \var{line} is the command line which was executed, and +\var{stop} is a flag which indicates whether execution will be +terminated after the call to \method{postcmd()}; this will be the +return value of the \method{onecmd()} method. The return value of +this method will be used as the new value for the internal flag which +corresponds to \var{stop}; returning false will cause interpretation +to continue. \end{methoddesc} \begin{methoddesc}{preloop}{} diff --git a/Doc/lib/libcookie.tex b/Doc/lib/libcookie.tex index c76e1237e3..66343e2482 100644 --- a/Doc/lib/libcookie.tex +++ b/Doc/lib/libcookie.tex @@ -28,18 +28,19 @@ whose values are \class{Morsel}s. Note that upon setting a key to a value, the value is first converted to a \class{Morsel} containing the key and the value. -If \var{input} is given, it is passed to the \method{load} method. +If \var{input} is given, it is passed to the \method{load()} method. \end{classdesc} \begin{classdesc}{SimpleCookie}{\optional{input}} -This class derives from \class{BaseCookie} and overrides \method{value_decode} -and \method{value_encode} to be the identity and \function{str()} respectively. +This class derives from \class{BaseCookie} and overrides +\method{value_decode()} and \method{value_encode()} to be the identity +and \function{str()} respectively. \end{classdesc} \begin{classdesc}{SerialCookie}{\optional{input}} -This class derives from \class{BaseCookie} and overrides \method{value_decode} -and \method{value_encode} to be the \function{pickle.loads()} and -\function{pickle.dumps}. +This class derives from \class{BaseCookie} and overrides +\method{value_decode()} and \method{value_encode()} to be the +\function{pickle.loads()} and \function{pickle.dumps()}. Do not use this class. Reading pickled values from a cookie is a security hole, as arbitrary client-code can be run on @@ -49,11 +50,11 @@ compatibility. \end{classdesc} \begin{classdesc}{SmartCookie}{\optional{input}} -This class derives from \class{BaseCookie}. It overrides \method{value_decode} -to be \function{pickle.loads()} if it is a valid pickle, and otherwise -the value itself. It overrides \method{value_encode} to be -\function{pickle.dumps()} unless it is a string, in which case it returns -the value itself. +This class derives from \class{BaseCookie}. It overrides +\method{value_decode()} to be \function{pickle.loads()} if it is a +valid pickle, and otherwise the value itself. It overrides +\method{value_encode()} to be \function{pickle.dumps()} unless it is a +string, in which case it returns the value itself. The same security warning from \class{SerialCookie} applies here. \end{classdesc} @@ -75,18 +76,19 @@ so it can be overridden. \begin{methoddesc}[BaseCookie]{value_encode}{val} Return an encoded value. \var{val} can be any type, but return value -must be a string. This method does nothing in \class{BaseCookie} --- it exists -so it can be overridden +must be a string. This method does nothing in \class{BaseCookie} --- +it exists so it can be overridden -In general, it should be the case that \method{value_encode} and -\method{value_decode} are inverses on the range of \var{value_decode}. -\end{methoddesc}. +In general, it should be the case that \method{value_encode()} and +\method{value_decode()} are inverses on the range of +\var{value_decode}. +\end{methoddesc} \begin{methoddesc}[BaseCookie]{output}{\optional{attrs\optional{, header\optional{, sep}}}} Return a string representation suitable to be sent as HTTP headers. -\var{attrs} and \var{header} are sent to each \class{Morsel}'s \method{output} -method. \var{sep} is used to join the headers together, and is by default -a newline. +\var{attrs} and \var{header} are sent to each \class{Morsel}'s +\method{output()} method. \var{sep} is used to join the headers +together, and is by default a newline. \end{methoddesc} \begin{methoddesc}[BaseCookie]{js_output}{\optional{attrs}} @@ -161,7 +163,7 @@ Return an embeddable JavaScript snippet, which, if run on a browser which supports JavaScript, will act the same as if the HTTP header was sent. The meaning for \var{attrs} is the same as in \method{output()}. -\end{methoddesc}. +\end{methoddesc} \begin{methoddesc}[Morsel]{OutputString}{\optional{attrs}} Return a string representing the Morsel, without any surrounding HTTP diff --git a/Doc/lib/libcrypt.tex b/Doc/lib/libcrypt.tex index e3936b7a5d..20d9bb2ad0 100644 --- a/Doc/lib/libcrypt.tex +++ b/Doc/lib/libcrypt.tex @@ -4,7 +4,7 @@ \declaremodule{builtin}{crypt} \platform{Unix} \modulesynopsis{The \cfunction{crypt()} function used to check - \UNIX{} passwords.} + \UNIX\ passwords.} \moduleauthor{Steven D. Majewski}{sdm7g@virginia.edu} \sectionauthor{Steven D. Majewski}{sdm7g@virginia.edu} \sectionauthor{Peter Funk}{pf@artcom-gmbh.de} diff --git a/Doc/lib/libcurses.tex b/Doc/lib/libcurses.tex index ef4444ab82..07686f9d0f 100644 --- a/Doc/lib/libcurses.tex +++ b/Doc/lib/libcurses.tex @@ -510,8 +510,8 @@ file descriptor for typeahead checking. \begin{funcdesc}{unctrl}{ch} Returns a string which is a printable representation of the character \var{ch}. Control characters are displayed as a caret followed by the -character, for example as \verb|^C|. Printing characters are left as they -are. +character, for example as \code{\textasciicircum C}. Printing +characters are left as they are. \end{funcdesc} \begin{funcdesc}{ungetch}{ch} @@ -541,7 +541,7 @@ Window objects, as returned by \function{initscr()} and \function{newwin()} above, have the following methods: -\begin{methoddesc}{addch}{\optional{y, x,} ch\optional{, attr}} +\begin{methoddesc}[window]{addch}{\optional{y, x,} ch\optional{, attr}} \strong{Note:} A \emph{character} means a C character (i.e., an \ASCII{} code), rather then a Python character (a string of length 1). (This note is true whenever the documentation mentions a character.) @@ -553,33 +553,33 @@ location. By default, the character position and attributes are the current settings for the window object. \end{methoddesc} -\begin{methoddesc}{addnstr}{\optional{y, x,} str, n\optional{, attr}} +\begin{methoddesc}[window]{addnstr}{\optional{y, x,} str, n\optional{, attr}} Paint at most \var{n} characters of the string \var{str} at \code{(\var{y}, \var{x})} with attributes \var{attr}, overwriting anything previously on the display. \end{methoddesc} -\begin{methoddesc}{addstr}{\optional{y, x,} str\optional{, attr}} +\begin{methoddesc}[window]{addstr}{\optional{y, x,} str\optional{, attr}} Paint the string \var{str} at \code{(\var{y}, \var{x})} with attributes \var{attr}, overwriting anything previously on the display. \end{methoddesc} -\begin{methoddesc}{attroff}{attr} +\begin{methoddesc}[window]{attroff}{attr} Remove attribute \var{attr} from the ``background'' set applied to all writes to the current window. \end{methoddesc} -\begin{methoddesc}{attron}{attr} +\begin{methoddesc}[window]{attron}{attr} Add attribute \var{attr} from the ``background'' set applied to all writes to the current window. \end{methoddesc} -\begin{methoddesc}{attrset}{attr} +\begin{methoddesc}[window]{attrset}{attr} Set the ``background'' set of attributes to \var{attr}. This set is initially 0 (no attributes). \end{methoddesc} -\begin{methoddesc}{bkgd}{ch\optional{, attr}} +\begin{methoddesc}[window]{bkgd}{ch\optional{, attr}} Sets the background property of the window to the character \var{ch}, with attributes \var{attr}. The change is then applied to every character position in that window: @@ -594,7 +594,7 @@ it is changed to the new background character. \end{methoddesc} -\begin{methoddesc}{bkgdset}{ch\optional{, attr}} +\begin{methoddesc}[window]{bkgdset}{ch\optional{, attr}} Sets the window's background. A window's background consists of a character and any combination of attributes. The attribute part of the background is combined (OR'ed) with all non-blank characters that @@ -605,9 +605,9 @@ character through any scrolling and insert/delete line/character operations. \end{methoddesc} -\begin{methoddesc}{border}{\optional{ls\optional{, rs\optional{, ts\optional{, - bs\optional{, tl\optional{, tr\optional{, - bl\optional{, br}}}}}}}}} +\begin{methoddesc}[window]{border}{\optional{ls\optional{, rs\optional{, + ts\optional{, bs\optional{, tl\optional{, + tr\optional{, bl\optional{, br}}}}}}}}} Draw a border around the edges of the window. Each parameter specifies the character to use for a specific part of the border; see the table below for more details. The characters must be specified as integers; @@ -630,46 +630,46 @@ can \emph{not} be used. The defaults are listed in this table: \end{tableiii} \end{methoddesc} -\begin{methoddesc}{box}{\optional{vertch, horch}} +\begin{methoddesc}[window]{box}{\optional{vertch, horch}} Similar to \method{border()}, but both \var{ls} and \var{rs} are \var{vertch} and both \var{ts} and {bs} are \var{horch}. The default corner characters are always used by this function. \end{methoddesc} -\begin{methoddesc}{clear}{} +\begin{methoddesc}[window]{clear}{} Like \method{erase()}, but also causes the whole window to be repainted upon next call to \method{refresh()}. \end{methoddesc} -\begin{methoddesc}{clearok}{yes} +\begin{methoddesc}[window]{clearok}{yes} If \var{yes} is 1, the next call to \method{refresh()} will clear the window completely. \end{methoddesc} -\begin{methoddesc}{clrtobot}{} +\begin{methoddesc}[window]{clrtobot}{} Erase from cursor to the end of the window: all lines below the cursor are deleted, and then the equivalent of \method{clrtoeol()} is performed. \end{methoddesc} -\begin{methoddesc}{clrtoeol}{} +\begin{methoddesc}[window]{clrtoeol}{} Erase from cursor to the end of the line. \end{methoddesc} -\begin{methoddesc}{cursyncup}{} +\begin{methoddesc}[window]{cursyncup}{} Updates the current cursor position of all the ancestors of the window to reflect the current cursor position of the window. \end{methoddesc} -\begin{methoddesc}{delch}{\optional{x, y}} +\begin{methoddesc}[window]{delch}{\optional{x, y}} Delete any character at \code{(\var{y}, \var{x})}. \end{methoddesc} -\begin{methoddesc}{deleteln}{} +\begin{methoddesc}[window]{deleteln}{} Delete the line under the cursor. All following lines are moved up by 1 line. \end{methoddesc} -\begin{methoddesc}{derwin}{\optional{nlines, ncols,} begin_y, begin_y} +\begin{methoddesc}[window]{derwin}{\optional{nlines, ncols,} begin_y, begin_x} An abbreviation for ``derive window'', \method{derwin()} is the same as calling \method{subwin()}, except that \var{begin_y} and \var{begin_x} are relative to the origin of the window, rather than @@ -677,67 +677,67 @@ relative to the entire screen. Returns a window object for the derived window. \end{methoddesc} -\begin{methoddesc}{echochar}{ch\optional{, attr}} +\begin{methoddesc}[window]{echochar}{ch\optional{, attr}} Add character \var{ch} with attribute \var{attr}, and immediately call \method{refresh()} on the window. \end{methoddesc} -\begin{methoddesc}{enclose}{y, x} +\begin{methoddesc}[window]{enclose}{y, x} Tests whether the given pair of screen-relative character-cell coordinates are enclosed by the given window, returning true or false. It is useful for determining what subset of the screen windows enclose the location of a mouse event. \end{methoddesc} -\begin{methoddesc}{erase}{} +\begin{methoddesc}[window]{erase}{} Clear the window. \end{methoddesc} -\begin{methoddesc}{getbegyx}{} +\begin{methoddesc}[window]{getbegyx}{} Return a tuple \code{(\var{y}, \var{x})} of co-ordinates of upper-left corner. \end{methoddesc} -\begin{methoddesc}{getch}{\optional{x, y}} +\begin{methoddesc}[window]{getch}{\optional{x, y}} Get a character. Note that the integer returned does \emph{not} have to be in \ASCII{} range: function keys, keypad keys and so on return numbers higher than 256. In no-delay mode, an exception is raised if there is no input. \end{methoddesc} -\begin{methoddesc}{getkey}{\optional{x, y}} +\begin{methoddesc}[window]{getkey}{\optional{x, y}} Get a character, returning a string instead of an integer, as \method{getch()} does. Function keys, keypad keys and so on return a multibyte string containing the key name. In no-delay mode, an exception is raised if there is no input. \end{methoddesc} -\begin{methoddesc}{getmaxyx}{} +\begin{methoddesc}[window]{getmaxyx}{} Return a tuple \code{(\var{y}, \var{x})} of the height and width of the window. \end{methoddesc} -\begin{methoddesc}{getparyx}{} +\begin{methoddesc}[window]{getparyx}{} Returns the beginning coordinates of this window relative to its parent window into two integer variables y and x. Returns \code{-1,-1} if this window has no parent. \end{methoddesc} -\begin{methoddesc}{getstr}{\optional{x, y}} +\begin{methoddesc}[window]{getstr}{\optional{x, y}} Read a string from the user, with primitive line editing capacity. \end{methoddesc} -\begin{methoddesc}{getyx}{} +\begin{methoddesc}[window]{getyx}{} Return a tuple \code{(\var{y}, \var{x})} of current cursor position relative to the window's upper-left corner. \end{methoddesc} -\begin{methoddesc}{hline}{\optional{y, x,} ch, n} +\begin{methoddesc}[window]{hline}{\optional{y, x,} ch, n} Display a horizontal line starting at \code{(\var{y}, \var{x})} with length \var{n} consisting of the character \var{ch}. \end{methoddesc} -\begin{methoddesc}{idcok}{flag} +\begin{methoddesc}[window]{idcok}{flag} If \var{flag} is false, curses no longer considers using the hardware insert/delete character feature of the terminal; if \var{flag} is true, use of character insertion and deletion is enabled. When curses @@ -745,13 +745,13 @@ is first initialized, use of character insert/delete is enabled by default. \end{methoddesc} -\begin{methoddesc}{idlok}{yes} +\begin{methoddesc}[window]{idlok}{yes} If called with \var{yes} equal to 1, \module{curses} will try and use hardware line editing facilities. Otherwise, line insertion/deletion are disabled. \end{methoddesc} -\begin{methoddesc}{immedok}{flag} +\begin{methoddesc}[window]{immedok}{flag} If \var{flag} is true, any change in the window image automatically causes the window to be refreshed; you no longer have to call \method{refresh()} yourself. However, it may @@ -759,18 +759,18 @@ degrade performance considerably, due to repeated calls to wrefresh. This option is disabled by default. \end{methoddesc} -\begin{methoddesc}{inch}{\optional{x, y}} +\begin{methoddesc}[window]{inch}{\optional{x, y}} Return the character at the given position in the window. The bottom 8 bits are the character proper, and upper bits are the attributes. \end{methoddesc} -\begin{methoddesc}{insch}{\optional{y, x,} ch\optional{, attr}} +\begin{methoddesc}[window]{insch}{\optional{y, x,} ch\optional{, attr}} Paint character \var{ch} at \code{(\var{y}, \var{x})} with attributes \var{attr}, moving the line from position \var{x} right by one character. \end{methoddesc} -\begin{methoddesc}{insdelln}{nlines} +\begin{methoddesc}[window]{insdelln}{nlines} Inserts \var{nlines} lines into the specified window above the current line. The \var{nlines} bottom lines are lost. For negative \var{nlines}, delete \var{nlines} lines starting with the one under @@ -778,12 +778,12 @@ the cursor, and move the remaining lines up. The bottom \var{nlines} lines are cleared. The current cursor position remains the same. \end{methoddesc} -\begin{methoddesc}{insertln}{} +\begin{methoddesc}[window]{insertln}{} Insert a blank line under the cursor. All following lines are moved down by 1 line. \end{methoddesc} -\begin{methoddesc}{insnstr}{\optional{y, x, } str, n \optional{, attr}} +\begin{methoddesc}[window]{insnstr}{\optional{y, x,} str, n \optional{, attr}} Insert a character string (as many characters as will fit on the line) before the character under the cursor, up to \var{n} characters. If \var{n} is zero or negative, @@ -794,7 +794,7 @@ line being lost. The cursor position does not change (after moving to \var{y}, \var{x}, if specified). \end{methoddesc} -\begin{methoddesc}{insstr}{\optional{y, x, } str \optional{, attr}} +\begin{methoddesc}[window]{insstr}{\optional{y, x, } str \optional{, attr}} Insert a character string (as many characters as will fit on the line) before the character under the cursor. All characters to the right of the cursor are shifted right, with the the rightmost characters on the @@ -802,7 +802,7 @@ line being lost. The cursor position does not change (after moving to \var{y}, \var{x}, if specified). \end{methoddesc} -\begin{methoddesc}{instr}{\optional{y, x} \optional{, n}} +\begin{methoddesc}[window]{instr}{\optional{y, x} \optional{, n}} Returns a string of characters, extracted from the window starting at the current cursor position, or at \var{y}, \var{x} if specified. Attributes are stripped from the characters. If \var{n} is specified, @@ -810,26 +810,26 @@ Attributes are stripped from the characters. If \var{n} is specified, long (exclusive of the trailing NUL). \end{methoddesc} -\begin{methoddesc}{is_linetouched}{\var{line}} +\begin{methoddesc}[window]{is_linetouched}{\var{line}} Returns true if the specified line was modified since the last call to \method{refresh()}; otherwise returns false. Raises a \exception{curses.error} exception if \var{line} is not valid for the given window. \end{methoddesc} -\begin{methoddesc}{is_wintouched}{} +\begin{methoddesc}[window]{is_wintouched}{} Returns true if the specified window was modified since the last call to \method{refresh()}; otherwise returns false. \end{methoddesc} -\begin{methoddesc}{keypad}{yes} +\begin{methoddesc}[window]{keypad}{yes} If \var{yes} is 1, escape sequences generated by some keys (keypad, function keys) will be interpreted by \module{curses}. If \var{yes} is 0, escape sequences will be left as is in the input stream. \end{methoddesc} -\begin{methoddesc}{leaveok}{yes} +\begin{methoddesc}[window]{leaveok}{yes} If \var{yes} is 1, cursor is left where it is on update, instead of being at ``cursor position.'' This reduces cursor movement where possible. If possible the cursor will be made invisible. @@ -838,42 +838,42 @@ If \var{yes} is 0, cursor will always be at ``cursor position'' after an update. \end{methoddesc} -\begin{methoddesc}{move}{new_y, new_x} +\begin{methoddesc}[window]{move}{new_y, new_x} Move cursor to \code{(\var{new_y}, \var{new_x})}. \end{methoddesc} -\begin{methoddesc}{mvderwin}{y, x} +\begin{methoddesc}[window]{mvderwin}{y, x} Moves the window inside its parent window. The screen-relative parameters of the window are not changed. This routine is used to display different parts of the parent window at the same physical position on the screen. \end{methoddesc} -\begin{methoddesc}{mvwin}{new_y, new_x} +\begin{methoddesc}[window]{mvwin}{new_y, new_x} Move the window so its upper-left corner is at \code{(\var{new_y}, \var{new_x})}. \end{methoddesc} -\begin{methoddesc}{nodelay}{yes} +\begin{methoddesc}[window]{nodelay}{yes} If \var{yes} is \code{1}, \method{getch()} will be non-blocking. \end{methoddesc} -\begin{methoddesc}{notimeout}{yes} +\begin{methoddesc}[window]{notimeout}{yes} If \var{yes} is \code{1}, escape sequences will not be timed out. If \var{yes} is \code{0}, after a few milliseconds, an escape sequence will not be interpreted, and will be left in the input stream as is. \end{methoddesc} -\begin{methoddesc}{noutrefresh}{} +\begin{methoddesc}[window]{noutrefresh}{} Mark for refresh but wait. This function updates the data structure representing the desired state of the window, but does not force an update of the physical screen. To accomplish that, call \function{doupdate()}. \end{methoddesc} -\begin{methoddesc}{overlay}{destwin\optional{, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol}} +\begin{methoddesc}[window]{overlay}{destwin\optional{, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol}} Overlay the window on top of \var{destwin}. The windows need not be the same size, only the overlapping region is copied. This copy is non-destructive, which means that the current background character @@ -885,8 +885,8 @@ the upper-left coordinates of the source window, and the other variables mark a rectangle in the destination window. \end{methoddesc} -\begin{methoddesc}{overwrite}{destwin\optional{, sminrow, smincol, - dminrow, dmincol, dmaxrow, dmaxcol}} +\begin{methoddesc}[window]{overwrite}{destwin\optional{, sminrow, smincol, + dminrow, dmincol, dmaxrow, dmaxcol}} Overwrite the window on top of \var{destwin}. The windows need not be the same size, in which case only the overlapping region is copied. This copy is destructive, which means that the current @@ -898,26 +898,25 @@ the upper-left coordinates of the source window, the other variables mark a rectangle in the destination window. \end{methoddesc} -\begin{methoddesc}{putwin}{file} +\begin{methoddesc}[window]{putwin}{file} Writes all data associated with the window into the provided file object. This information can be later retrieved using the \function{getwin()} function. - \end{methoddesc} -\begin{methoddesc}{redrawln}{beg, num} +\begin{methoddesc}[window]{redrawln}{beg, num} Indicates that the \var{num} screen lines, starting at line \var{beg}, are corrupted and should be completely redrawn on the next \method{refresh()} call. \end{methoddesc} -\begin{methoddesc}{redrawwin}{} +\begin{methoddesc}[window]{redrawwin}{} Touches the entire window, causing it to be completely redrawn on the next \method{refresh()} call. \end{methoddesc} -\begin{methoddesc}{refresh}{\optional{pminrow, pmincol, sminrow, - smincol, smaxrow, smaxcol}} +\begin{methoddesc}[window]{refresh}{\optional{pminrow, pmincol, sminrow, + smincol, smaxrow, smaxcol}} Update the display immediately (sync actual screen with previous drawing/deleting methods). @@ -935,11 +934,11 @@ structures. Negative values of \var{pminrow}, \var{pmincol}, \var{sminrow}, or \var{smincol} are treated as if they were zero. \end{methoddesc} -\begin{methoddesc}{scroll}{\optional{lines\code{ = 1}}} +\begin{methoddesc}[window]{scroll}{\optional{lines\code{ = 1}}} Scroll the screen or scrolling region upward by \var{lines} lines. \end{methoddesc} -\begin{methoddesc}{scrollok}{flag} +\begin{methoddesc}[window]{scrollok}{flag} Controls what happens when the cursor of a window is moved off the edge of the window or scrolling region, either as a result of a newline action on the bottom line, or typing the last character @@ -950,27 +949,27 @@ scrolling effect on the terminal, it is also necessary to call \method{idlok()}. \end{methoddesc} -\begin{methoddesc}{setscrreg}{top, bottom} +\begin{methoddesc}[window]{setscrreg}{top, bottom} Set the scrolling region from line \var{top} to line \var{bottom}. All scrolling actions will take place in this region. \end{methoddesc} -\begin{methoddesc}{standend}{} +\begin{methoddesc}[window]{standend}{} Turn off the standout attribute. On some terminals this has the side effect of turning off all attributes. \end{methoddesc} -\begin{methoddesc}{standout}{} +\begin{methoddesc}[window]{standout}{} Turn on attribute \var{A_STANDOUT}. \end{methoddesc} -\begin{methoddesc}{subpad}{\optional{nlines, ncols,} begin_y, begin_y} +\begin{methoddesc}[window]{subpad}{\optional{nlines, ncols,} begin_y, begin_x} Return a sub-window, whose upper-left corner is at \code{(\var{begin_y}, \var{begin_x})}, and whose width/height is \var{ncols}/\var{nlines}. \end{methoddesc} -\begin{methoddesc}{subwin}{\optional{nlines, ncols,} begin_y, begin_y} +\begin{methoddesc}[window]{subwin}{\optional{nlines, ncols,} begin_y, begin_x} Return a sub-window, whose upper-left corner is at \code{(\var{begin_y}, \var{begin_x})}, and whose width/height is \var{ncols}/\var{nlines}. @@ -979,23 +978,23 @@ By default, the sub-window will extend from the specified position to the lower right corner of the window. \end{methoddesc} -\begin{methoddesc}{syncdown}{} +\begin{methoddesc}[window]{syncdown}{} Touches each location in the window that has been touched in any of its ancestor windows. This routine is called by \method{refresh()}, so it should almost never be necessary to call it manually. \end{methoddesc} -\begin{methoddesc}{syncok}{flag} +\begin{methoddesc}[window]{syncok}{flag} If called with \var{flag} set to true, then \method{syncup()} is called automatically whenever there is a change in the window. \end{methoddesc} -\begin{methoddesc}{syncup}{} +\begin{methoddesc}[window]{syncup}{} Touches all locations in ancestors of the window that have been changed in the window. \end{methoddesc} -\begin{methoddesc}{timeout}{delay} +\begin{methoddesc}[window]{timeout}{delay} Sets blocking or non-blocking read behavior for the window. If \var{delay} is negative, blocking read is used, which will wait indefinitely for input). If \var{delay} is zero, then non-blocking @@ -1005,22 +1004,22 @@ block for \var{delay} milliseconds, and return -1 if there is still no input at the end of that time. \end{methoddesc} -\begin{methoddesc}{touchline}{start, count} +\begin{methoddesc}[window]{touchline}{start, count} Pretend \var{count} lines have been changed, starting with line \var{start}. \end{methoddesc} -\begin{methoddesc}{touchwin}{} +\begin{methoddesc}[window]{touchwin}{} Pretend the whole window has been changed, for purposes of drawing optimizations. \end{methoddesc} -\begin{methoddesc}{untouchwin}{} +\begin{methoddesc}[window]{untouchwin}{} Marks all lines in the window as unchanged since the last call to \method{refresh()}. \end{methoddesc} -\begin{methoddesc}{vline}{\optional{y, x,} ch, n} +\begin{methoddesc}[window]{vline}{\optional{y, x,} ch, n} Display a vertical line starting at \code{(\var{y}, \var{x})} with length \var{n} consisting of the character \var{ch}. \end{methoddesc} diff --git a/Doc/lib/libdbhash.tex b/Doc/lib/libdbhash.tex index 61b01639fd..4b856de0b8 100644 --- a/Doc/lib/libdbhash.tex +++ b/Doc/lib/libdbhash.tex @@ -21,7 +21,7 @@ This module provides an exception and a function: \exception{KeyError}. It is a synonym for \exception{bsddb.error}. \end{excdesc} -\begin{funcdesc}{open}{path, flag\optional{, mode}} +\begin{funcdesc}{open}{path\optional{, flag\optional{, mode}}} Open a \code{db} database and return the database object. The \var{path} argument is the name of the database file. diff --git a/Doc/lib/libdoctest.tex b/Doc/lib/libdoctest.tex index 6d19259d25..9b99b9d51d 100644 --- a/Doc/lib/libdoctest.tex +++ b/Doc/lib/libdoctest.tex @@ -406,6 +406,17 @@ often contrive doctest examples to produce numbers of that form: Simple fractions are also easier for people to understand, and that makes for better documentation. + +\item Be careful if you have code that must only execute once. + +If you have module-level code that must only execute once, a more foolproof +definition of \function{_test()} is + +\begin{verbatim} +def _test(): + import doctest, sys + doctest.testmod(sys.modules["__main__"]) +\end{verbatim} \end{enumerate} diff --git a/Doc/lib/libfileinput.tex b/Doc/lib/libfileinput.tex index 97caaf9e46..c66501f21d 100644 --- a/Doc/lib/libfileinput.tex +++ b/Doc/lib/libfileinput.tex @@ -47,7 +47,9 @@ The following function is the primary interface of this module: inplace\optional{, backup}}}} Create an instance of the \class{FileInput} class. The instance will be used as global state for the functions of this module, and - is also returned to use during iteration. + is also returned to use during iteration. The parameters to this + function will be passed along to the constructor of the + \class{FileInput} class. \end{funcdesc} @@ -118,7 +120,8 @@ module is available for subclassing as well: \strong{Optional in-place filtering:} if the keyword argument \code{\var{inplace}=1} is passed to \function{input()} or to the \class{FileInput} constructor, the file is moved to a backup file and -standard output is directed to the input file. +standard output is directed to the input file (if a file of the same +name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the keyword argument \code{\var{backup}='.'} is also given, it specifies the extension for the backup diff --git a/Doc/lib/libfpectl.tex b/Doc/lib/libfpectl.tex index 53c3406aff..814e226575 100644 --- a/Doc/lib/libfpectl.tex +++ b/Doc/lib/libfpectl.tex @@ -2,7 +2,7 @@ Floating point exception control} \declaremodule{extension}{fpectl} - \platform{Unix, Windows} + \platform{Unix} \moduleauthor{Lee Busby}{busby1@llnl.gov} \sectionauthor{Lee Busby}{busby1@llnl.gov} \modulesynopsis{Provide control for floating point exception handling.} @@ -18,7 +18,7 @@ For example, try >>> import math >>> math.exp(1000) inf ->>> math.exp(1000)/math.exp(1000) +>>> math.exp(1000) / math.exp(1000) nan \end{verbatim} diff --git a/Doc/lib/libgetopt.tex b/Doc/lib/libgetopt.tex index c96c3cfff4..fff30430e0 100644 --- a/Doc/lib/libgetopt.tex +++ b/Doc/lib/libgetopt.tex @@ -64,6 +64,9 @@ not require one will also cause this exception to be raised. The attributes \member{msg} and \member{opt} give the error message and related option; if there is no specific option to which the exception relates, \member{opt} is an empty string. + +\versionchanged[Introduced \exception{GetoptError} as a synonym for + \exception{error}]{1.6} \end{excdesc} \begin{excdesc}{error} diff --git a/Doc/lib/liblocale.tex b/Doc/lib/liblocale.tex index 107c21de7f..14afdccf7c 100644 --- a/Doc/lib/liblocale.tex +++ b/Doc/lib/liblocale.tex @@ -300,16 +300,14 @@ should you document that your module is not compatible with non-\samp{C} locale settings. The case conversion functions in the -\refmodule{string}\refstmodindex{string} and -\module{strop}\refbimodindex{strop} modules are affected by the locale -settings. When a call to the \function{setlocale()} function changes -the \constant{LC_CTYPE} settings, the variables +\refmodule{string}\refstmodindex{string} module are affected by the +locale settings. When a call to the \function{setlocale()} function +changes the \constant{LC_CTYPE} settings, the variables \code{string.lowercase}, \code{string.uppercase} and -\code{string.letters} (and their counterparts in \module{strop}) are -recalculated. Note that this code that uses these variable through -`\keyword{from} ... \keyword{import} ...', e.g. \code{from string -import letters}, is not affected by subsequent \function{setlocale()} -calls. +\code{string.letters} are recalculated. Note that this code that uses +these variable through `\keyword{from} ... \keyword{import} ...', +e.g.\ \code{from string import letters}, is not affected by subsequent +\function{setlocale()} calls. The only way to perform numeric operations according to the locale is to use the special functions defined by this module: diff --git a/Doc/lib/libmpz.tex b/Doc/lib/libmpz.tex index f0d2d6b152..e19ee565b4 100644 --- a/Doc/lib/libmpz.tex +++ b/Doc/lib/libmpz.tex @@ -96,3 +96,16 @@ An mpz-number has one method: The mpz-number must have a value greater than or equal to zero, otherwise \exception{ValueError} will be raised. \end{methoddesc} + + +\begin{seealso} + \seetitle[http://gmpy.sourceforge.net/]{General Multiprecision Python}{ + This project is building new numeric types to allow + arbitrary-precision arithmetic in Python. Their first + efforts are also based on the GNU MP library.} + + \seetitle[http://www.egenix.com/files/python/mxNumber.html]{mxNumber + --- Extended Numeric Types for Python}{Another wrapper + around the GNU MP library, including a port of that + library to Windows.} +\end{seealso} diff --git a/Doc/lib/libos.tex b/Doc/lib/libos.tex index 6ea9349f41..ca9a206d85 100644 --- a/Doc/lib/libos.tex +++ b/Doc/lib/libos.tex @@ -166,6 +166,13 @@ Return the current process' user id. Availability: \UNIX{}. \end{funcdesc} +\begin{funcdesc}{getenv}{varname\optional{, value}} +Return the value of the environment variable \var{varname} if it +exists, or \var{value} if it doesn't. \var{value} defaults to +\code{None}. +Availability: most flavors of \UNIX{}, Windows. +\end{funcdesc} + \begin{funcdesc}{putenv}{varname, value} \index{environment variables!setting} Set the environment variable named \var{varname} to the string @@ -307,21 +314,24 @@ specified, it specifies the buffer size for the I/O pipes. objects should be opened in binary or text mode. The default value for \var{mode} is \code{'t'}. -\begin{funcdesc}{popen2}{cmd\optional{, bufsize\optional{, mode}}} +\begin{funcdesc}{popen2}{cmd\optional{, mode\optional{, bufsize}}} Executes \var{cmd} as a sub-process. Returns the file objects \code{(\var{child_stdin}, \var{child_stdout})}. +Availability: \UNIX{}, Windows. \versionadded{2.0} \end{funcdesc} -\begin{funcdesc}{popen3}{cmd\optional{, bufsize\optional{, mode}}} +\begin{funcdesc}{popen3}{cmd\optional{, mode\optional{, bufsize}}} Executes \var{cmd} as a sub-process. Returns the file objects \code{(\var{child_stdin}, \var{child_stdout}, \var{child_stderr})}. +Availability: \UNIX{}, Windows. \versionadded{2.0} \end{funcdesc} -\begin{funcdesc}{popen4}{cmd\optional{, bufsize\optional{, mode}}} +\begin{funcdesc}{popen4}{cmd\optional{, mode\optional{, bufsize}}} Executes \var{cmd} as a sub-process. Returns the file objects \code{(\var{child_stdin}, \var{child_stdout_and_stderr})}. +Availability: \UNIX{}, Windows. \versionadded{2.0} \end{funcdesc} @@ -650,14 +660,20 @@ Availability: \UNIX. \begin{funcdesc}{readlink}{path} Return a string representing the path to which the symbolic link -points. +points. The result may be either an absolute or relative pathname; if +it is relative, it may be converted to an absolute pathname using +\code{os.path.join(os.path.dirname(\var{path}), \var{result})}. Availability: \UNIX{}. \end{funcdesc} \begin{funcdesc}{remove}{path} -Remove the file \var{path}. See \function{rmdir()} below to remove a -directory. This is identical to the \function{unlink()} function -documented below. +Remove the file \var{path}. If \var{path} is a directory, +\exception{OSError} is raised; see \function{rmdir()} below to remove +a directory. This is identical to the \function{unlink()} function +documented below. On Windows, attempting to remove a file that is in +use causes an exception to be raised; on \UNIX, the directory entry is +removed but the storage allocated to the file is not made available +until the original file is no longer in use. Availability: Macintosh, \UNIX{}, Windows. \end{funcdesc} @@ -674,7 +690,16 @@ exception if the leaf directory could not be successfully removed. \end{funcdesc} \begin{funcdesc}{rename}{src, dst} -Rename the file or directory \var{src} to \var{dst}. +Rename the file or directory \var{src} to \var{dst}. If \var{dst} is +a directory, \exception{OSError} will be raised. On \UNIX, if +\var{dst} exists and is a file, it will be removed silently if the +user has permission. The operation may fail on some \UNIX{} flavors +if \var{src} and \var{dst} are on different filesystems. If +successful, the renaming will be an atomic operation (this is a +\POSIX{} requirement). On Windows, if \var{dst} already exists, +\exception{OSError} will be raised even if it is a file; there may be +no way to implement an atomic rename when \var{dst} names an existing +file. Availability: Macintosh, \UNIX{}, Windows. \end{funcdesc} @@ -756,6 +781,7 @@ files if \var{dir} is omitted or \code{None}. If given and not filename. Applications are responsible for properly creating and managing files created using paths returned by \function{tempnam()}; no automatic cleanup is provided. +Availability: \UNIX. \end{funcdesc} \begin{funcdesc}{tmpnam}{} @@ -765,11 +791,13 @@ entry in a common location for temporary files. Applications are responsible for properly creating and managing files created using paths returned by \function{tmpnam()}; no automatic cleanup is provided. +Availability: \UNIX. \end{funcdesc} \begin{datadesc}{TMP_MAX} The maximum number of unique names that \function{tmpnam()} will generate before reusing names. +Availability: \UNIX, Windows. \end{datadesc} \begin{funcdesc}{unlink}{path} @@ -906,6 +934,14 @@ Lock program segments into memory. The value of \var{op} Availability: \UNIX{}. \end{funcdesc} +\begin{funcdescni}{popen}{\unspecified} +\funclineni{popen2}{\unspecified} +\funclineni{popen3}{\unspecified} +\funclineni{popen4}{\unspecified} +Run child processes, returning opened pipes for communications. These +functions are described in section \ref{os-newstreams}. +\end{funcdescni} + \begin{funcdesc}{spawnv}{mode, path, args} Execute the program \var{path} in a new process, passing the arguments specified in \var{args} as command-line parameters. \var{args} may be @@ -914,7 +950,7 @@ the Visual \Cpp{} Runtime Library documentation for further information; the constants are exposed to the Python programmer as listed below. Availability: \UNIX{}, Windows. -\versionadded{1.5.2} +\versionadded{1.6} \end{funcdesc} \begin{funcdesc}{spawnve}{mode, path, args, env} @@ -925,7 +961,7 @@ a tuple. \var{mode} is a magic operational constant. See the Visual \Cpp{} Runtime Library documentation for further information; the constants are exposed to the Python programmer as listed below. Availability: \UNIX{}, Windows. -\versionadded{1.5.2} +\versionadded{1.6} \end{funcdesc} \begin{datadesc}{P_WAIT} @@ -934,7 +970,7 @@ Availability: \UNIX{}, Windows. Possible values for the \var{mode} parameter to \function{spawnv()} and \function{spawnve()}. Availability: \UNIX{}, Windows. -\versionadded{1.5.2} +\versionadded{1.6} \end{datadesc} \begin{datadesc}{P_OVERLAY} @@ -943,7 +979,7 @@ Possible values for the \var{mode} parameter to \function{spawnv()} and \function{spawnve()}. These are less portable than those listed above. Availability: Windows. -\versionadded{1.5.2} +\versionadded{1.6} \end{datadesc} \begin{funcdesc}{startfile}{path} diff --git a/Doc/lib/libpipes.tex b/Doc/lib/libpipes.tex index 2b1763b0ea..4e6ea53930 100644 --- a/Doc/lib/libpipes.tex +++ b/Doc/lib/libpipes.tex @@ -4,7 +4,7 @@ \declaremodule{standard}{pipes} \platform{Unix} \sectionauthor{Moshe Zadka}{moshez@zadka.site.co.il} -\modulesynopsis{A Python interface to \UNIX{} shell pipelines.} +\modulesynopsis{A Python interface to \UNIX\ shell pipelines.} The \module{pipes} module defines a class to abstract the concept of diff --git a/Doc/lib/libpopen2.tex b/Doc/lib/libpopen2.tex index 699308c2a0..add0af130c 100644 --- a/Doc/lib/libpopen2.tex +++ b/Doc/lib/libpopen2.tex @@ -77,7 +77,12 @@ code otherwise. \end{methoddesc} \begin{methoddesc}{wait}{} -Waits for and returns the return code of the child process. +Waits for and returns the status code of the child process. The +status code encodes both the return code of the process and +information about whether it exited using the \cfunction{exit()} +system call or died due to a signal. Functions to help interpret the +status code are defined in the \refmodule{os} module; see section +\ref{os-process} for the \function{W\var{*}()} family of functions. \end{methoddesc} diff --git a/Doc/lib/libpoplib.tex b/Doc/lib/libpoplib.tex index 89e7e0c841..1df47e74cc 100644 --- a/Doc/lib/libpoplib.tex +++ b/Doc/lib/libpoplib.tex @@ -20,8 +20,8 @@ optional command sets. Note that POP3, though widely supported, is obsolescent. The implementation quality of POP3 servers varies widely, and too many are quite poor. If your mailserver supports IMAP, you would be better off -using the \refmodule{IMAP} class, as IMAP servers tend to be better -implemented. +using the \code{\refmodule{imaplib}.\class{IMAP4}} class, as IMAP +servers tend to be better implemented. A single class is provided by the \module{poplib} module: @@ -38,6 +38,14 @@ Exception raised on any errors. The reason for the exception is passed to the constructor as a string. \end{excdesc} +\begin{seealso} + \seemodule{imaplib}{The standard Python IMAP module.} + \seetitle{http://www.tuxedo.org/~esr/fetchail/fetchmail-FAQ.html}{ + The FAQ for the fetchmail POP/IMAP client collects information + on POP3 server variations and RFC noncompliance that may be + useful if you need to write an application based on poplib.} +\end{seealso} + \subsection{POP3 Objects \label{pop3-objects}} @@ -125,13 +133,6 @@ otherwise result is list \code{(\var{response}, ['mesgnum uid', ...], \var{octets})}. \end{methoddesc} -\begin{seealso} - \seemodule{imap}{The standard Python IMAP module.} - \seetitle{http://www.tuxedo.org/~esr/fetchail/fetchmail-FAQ.html}{ - The FAQ for the fetchmail POP/IMAP client collects information - on POP3 server variations and RFC noncompliance that may be - useful if you need to write an application based on poplib.} -\end{seealso} \subsection{POP3 Example \label{pop3-example}} diff --git a/Doc/lib/libposix.tex b/Doc/lib/libposix.tex index dada973011..201a53ba1a 100644 --- a/Doc/lib/libposix.tex +++ b/Doc/lib/libposix.tex @@ -3,7 +3,7 @@ \declaremodule{builtin}{posix} \platform{Unix} -\modulesynopsis{The most common \POSIX{} system calls (normally used +\modulesynopsis{The most common \POSIX\ system calls (normally used via module \refmodule{os}).} @@ -55,16 +55,13 @@ this mode. For example, it is enabled by default with recent versions of Irix, but with Solaris 2.6 and 2.7 you need to do something like: \begin{verbatim} -CFLAGS="`getconf LFS_CFLAGS`" OPT="-g -O2 $CFLAGS" \ - ./configure -\end{verbatim} % $ <-- bow to font-lock +CC="cc `getconf LFS_CFLAGS`" ./configure +\end{verbatim} On large-file-capable Linux systems, this might work: \begin{verbatim} -CC="-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64" -export CC -./configure +CC='gcc -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' ./configure \end{verbatim} diff --git a/Doc/lib/libposixpath.tex b/Doc/lib/libposixpath.tex index f585f41c42..658b4eaa0c 100644 --- a/Doc/lib/libposixpath.tex +++ b/Doc/lib/libposixpath.tex @@ -181,6 +181,7 @@ Split the pathname \var{path} into a pair \code{(\var{drive}, empty string. On systems which do not use drive specifications, \var{drive} will always be the empty string. In all cases, \code{\var{drive} + \var{tail}} will be the same as \var{path}. +\versionadded{1.3} \end{funcdesc} \begin{funcdesc}{splitext}{path} diff --git a/Doc/lib/libprofile.tex b/Doc/lib/libprofile.tex index a8861c3f8a..1372a0ae7e 100644 --- a/Doc/lib/libprofile.tex +++ b/Doc/lib/libprofile.tex @@ -449,7 +449,7 @@ now that ascending vs descending order is properly selected based on the sort key of choice. \end{methoddesc} -\begin{methoddesc}[Stats]{print_stats}{restriction\optional{, ...}} +\begin{methoddesc}[Stats]{print_stats}{\optional{restriction, \moreargs}} This method for the \class{Stats} class prints out a report as described in the \function{profile.run()} definition. @@ -484,7 +484,7 @@ and then proceed to only print the first 10\% of them. \end{methoddesc} -\begin{methoddesc}[Stats]{print_callers}{restrictions\optional{, ...}} +\begin{methoddesc}[Stats]{print_callers}{\optional{restriction, \moreargs}} This method for the \class{Stats} class prints a list of all functions that called each function in the profiled database. The ordering is identical to that provided by \method{print_stats()}, and the definition @@ -494,7 +494,7 @@ times this specific call was made. A second non-parenthesized number is the cumulative time spent in the function at the right. \end{methoddesc} -\begin{methoddesc}[Stats]{print_callees}{restrictions\optional{, ...}} +\begin{methoddesc}[Stats]{print_callees}{\optional{restriction, \moreargs}} This method for the \class{Stats} class prints a list of all function that were called by the indicated function. Aside from this reversal of direction of calls (re: called vs was called by), the arguments and @@ -616,7 +616,7 @@ t = t[0] + t[1] - self.t # no calibration constant You can also achieve the same results using a derived class (and the profiler will actually run equally fast!!), but the above method is the simplest to use. I could have made the profiler ``self -calibrating'', but it would have made the initialization of the +calibrating,'' but it would have made the initialization of the profiler class slower, and would have required some \emph{very} fancy coding, or else the use of a variable where the constant \samp{.00053} was placed in the code shown. This is a \strong{VERY} critical @@ -665,6 +665,8 @@ constant :-). \subsection{OldProfile Class \label{profile-old}} +\deprecated{2.1.2}{This class will be removed in Python 2.2.} + The following derived profiler simulates the old style profiler, providing errant results on recursive functions. The reason for the usefulness of this profiler is that it runs faster (i.e., less @@ -727,6 +729,8 @@ class OldProfile(Profile): \subsection{HotProfile Class \label{profile-HotProfile}} +\deprecated{2.1.2}{This class will be removed in Python 2.2.} + This profiler is the fastest derived profile example. It does not calculate caller-callee relationships, and does not calculate cumulative time under a function. It only calculates time spent in a diff --git a/Doc/lib/librandom.tex b/Doc/lib/librandom.tex index e2e24e128d..69932604bf 100644 --- a/Doc/lib/librandom.tex +++ b/Doc/lib/librandom.tex @@ -98,10 +98,10 @@ Bookkeeping functions: \begin{funcdesc}{seed}{\optional{x}} Initialize the basic random number generator. Optional argument \var{x} can be any hashable object. - If \var(x) is omitted or \code{None}, current system time is used; + If \var{x} is omitted or \code{None}, current system time is used; current system time is also used to initialize the generator when the module is first imported. - If \var(x) is not \code{None} or an int or long, + If \var{x} is not \code{None} or an int or long, \code{hash(\var{x})} is used instead. If \var{x} is an int or long, \var{x} is used directly. Distinct values between 0 and 27814431486575L inclusive are guaranteed @@ -137,7 +137,7 @@ Bookkeeping functions: Change the internal state to what it would be if \function{random()} were called \var{n} times, but do so quickly. \var{n} is a non-negative integer. This is most useful in multi-threaded - programs, in conjuction with multiple instances of the \var{Random} + programs, in conjuction with multiple instances of the \class{Random} class: \method{setstate()} or \method{seed()} can be used to force all instances into the same internal state, and then \method{jumpahead()} can be used to force the instances' states as diff --git a/Doc/lib/libre.tex b/Doc/lib/libre.tex index cc92f13f6f..414f1b5bf5 100644 --- a/Doc/lib/libre.tex +++ b/Doc/lib/libre.tex @@ -391,7 +391,7 @@ result = re.match(pat, str) but the version using \function{compile()} is more efficient when the expression will be used several times in a single program. %(The compiled version of the last pattern passed to -%\function{regex.match()} or \function{regex.search()} is cached, so +%\function{re.match()} or \function{re.search()} is cached, so %programs that use only a single regular expression at a time needn't %worry about compiling regular expressions.) \end{funcdesc} @@ -514,9 +514,8 @@ replacement string. For example: 'pro--gram files' \end{verbatim} -The pattern may be a string or a -regex object; if you need to specify -regular expression flags, you must use a regex object, or use +The pattern may be a string or an RE object; if you need to specify +regular expression flags, you must use a RE object, or use embedded modifiers in a pattern; e.g. \samp{sub("(?i)b+", "x", "bbbb BBBB")} returns \code{'x x'}. @@ -623,7 +622,7 @@ Identical to the \function{subn()} function, using the compiled pattern. \begin{memberdesc}[RegexObject]{flags} -The flags argument used when the regex object was compiled, or +The flags argument used when the RE object was compiled, or \code{0} if no flags were provided. \end{memberdesc} @@ -634,7 +633,7 @@ symbolic groups were used in the pattern. \end{memberdesc} \begin{memberdesc}[RegexObject]{pattern} -The pattern string from which the regex object was compiled. +The pattern string from which the RE object was compiled. \end{memberdesc} @@ -663,7 +662,7 @@ the string matching the the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an \exception{IndexError} exception is raised. If a group is contained in a part of the pattern that did not match, -the corresponding result is \code{-1}. If a group is contained in a +the corresponding result is \code{None}. If a group is contained in a part of the pattern that matched multiple times, the last match is returned. @@ -732,14 +731,14 @@ Note that if \var{group} did not contribute to the match, this is \begin{memberdesc}[MatchObject]{pos} The value of \var{pos} which was passed to the -\function{search()} or \function{match()} function. This is the index into -the string at which the regex engine started looking for a match. +\function{search()} or \function{match()} function. This is the index +into the string at which the RE engine started looking for a match. \end{memberdesc} \begin{memberdesc}[MatchObject]{endpos} The value of \var{endpos} which was passed to the -\function{search()} or \function{match()} function. This is the index into -the string beyond which the regex engine will not go. +\function{search()} or \function{match()} function. This is the index +into the string beyond which the RE engine will not go. \end{memberdesc} \begin{memberdesc}[MatchObject]{lastgroup} diff --git a/Doc/lib/libresource.tex b/Doc/lib/libresource.tex index 869bb17125..7e7e9c2c5f 100644 --- a/Doc/lib/libresource.tex +++ b/Doc/lib/libresource.tex @@ -67,7 +67,9 @@ used by \C{} programs. The \UNIX{} man page for \manpage{getrlimit}{2} lists the available resources. Note that not all systems use the same symbol or same -value to denote the same resource. +value to denote the same resource. This module does not attempt to +mask platform differences --- symbols not defined for a platform will +not be available from this module on that platform. \begin{datadesc}{RLIMIT_CORE} The maximum size (in bytes) of a core file that the current process diff --git a/Doc/lib/librexec.tex b/Doc/lib/librexec.tex index 1c4c77c2e8..1f56a984b8 100644 --- a/Doc/lib/librexec.tex +++ b/Doc/lib/librexec.tex @@ -46,62 +46,28 @@ If \var{verbose} is true, additional debugging output may be sent to standard output. \end{classdesc} -The \class{RExec} class has the following class attributes, which are -used by the \method{__init__()} method. Changing them on an existing -instance won't have any effect; instead, create a subclass of -\class{RExec} and assign them new values in the class definition. -Instances of the new class will then use those new values. All these -attributes are tuples of strings. +It is important to be aware that code running in a restricted +environment can still call the \function{sys.exit()} function. To +disallow restricted code from exiting the interpreter, always protect +calls that cause restricted code to run with a +\keyword{try}/\keyword{except} statement that catches the +\exception{SystemExit} exception. Removing the \function{sys.exit()} +function from the restricted environment is not sufficient --- the +restricted code could still use \code{raise SystemExit}. Removing +\exception{SystemExit} is not a reasonable option; some library code +makes use of this and would break were it not available. -\begin{memberdesc}{nok_builtin_names} -Contains the names of built-in functions which will \emph{not} be -available to programs running in the restricted environment. The -value for \class{RExec} is \code{('open',} \code{'reload',} -\code{'__import__')}. (This gives the exceptions, because by far the -majority of built-in functions are harmless. A subclass that wants to -override this variable should probably start with the value from the -base class and concatenate additional forbidden functions --- when new -dangerous built-in functions are added to Python, they will also be -added to this module.) -\end{memberdesc} - -\begin{memberdesc}{ok_builtin_modules} -Contains the names of built-in modules which can be safely imported. -The value for \class{RExec} is \code{('audioop',} \code{'array',} -\code{'binascii',} \code{'cmath',} \code{'errno',} \code{'imageop',} -\code{'marshal',} \code{'math',} \code{'md5',} \code{'operator',} -\code{'parser',} \code{'regex',} \code{'rotor',} \code{'select',} -\code{'strop',} \code{'struct',} \code{'time')}. A similar remark -about overriding this variable applies --- use the value from the base -class as a starting point. -\end{memberdesc} - -\begin{memberdesc}{ok_path} -Contains the directories which will be searched when an \keyword{import} -is performed in the restricted environment. -The value for \class{RExec} is the same as \code{sys.path} (at the time -the module is loaded) for unrestricted code. -\end{memberdesc} -\begin{memberdesc}{ok_posix_names} -% Should this be called ok_os_names? -Contains the names of the functions in the \refmodule{os} module which will be -available to programs running in the restricted environment. The -value for \class{RExec} is \code{('error',} \code{'fstat',} -\code{'listdir',} \code{'lstat',} \code{'readlink',} \code{'stat',} -\code{'times',} \code{'uname',} \code{'getpid',} \code{'getppid',} -\code{'getcwd',} \code{'getuid',} \code{'getgid',} \code{'geteuid',} -\code{'getegid')}. -\end{memberdesc} +\begin{seealso} + \seetitle[http://grail.sourceforge.net/]{Grail Home Page}{Grail is a + Web browser written entirely in Python. It uses the + \module{rexec} module as a foundation for supporting + Python applets, and can be used as an example usage of + this module.} +\end{seealso} -\begin{memberdesc}{ok_sys_names} -Contains the names of the functions and variables in the \refmodule{sys} -module which will be available to programs running in the restricted -environment. The value for \class{RExec} is \code{('ps1',} -\code{'ps2',} \code{'copyright',} \code{'version',} \code{'platform',} -\code{'exit',} \code{'maxint')}. -\end{memberdesc} +\subsection{RExec Objects \label{rexec-objects}} \class{RExec} instances support the following methods: @@ -190,6 +156,61 @@ Unload the module object \var{module}. % XXX what are the semantics of this? \end{methoddesc} + +\subsection{Defining restricted environments \label{rexec-extension}} + +The \class{RExec} class has the following class attributes, which are +used by the \method{__init__()} method. Changing them on an existing +instance won't have any effect; instead, create a subclass of +\class{RExec} and assign them new values in the class definition. +Instances of the new class will then use those new values. All these +attributes are tuples of strings. + +\begin{memberdesc}{nok_builtin_names} +Contains the names of built-in functions which will \emph{not} be +available to programs running in the restricted environment. The +value for \class{RExec} is \code{('open', 'reload', '__import__')}. +(This gives the exceptions, because by far the majority of built-in +functions are harmless. A subclass that wants to override this +variable should probably start with the value from the base class and +concatenate additional forbidden functions --- when new dangerous +built-in functions are added to Python, they will also be added to +this module.) +\end{memberdesc} + +\begin{memberdesc}{ok_builtin_modules} +Contains the names of built-in modules which can be safely imported. +The value for \class{RExec} is \code{('audioop', 'array', 'binascii', +'cmath', 'errno', 'imageop', 'marshal', 'math', 'md5', 'operator', +'parser', 'regex', 'rotor', 'select', 'strop', 'struct', 'time')}. A +similar remark about overriding this variable applies --- use the +value from the base class as a starting point. +\end{memberdesc} + +\begin{memberdesc}{ok_path} +Contains the directories which will be searched when an \keyword{import} +is performed in the restricted environment. +The value for \class{RExec} is the same as \code{sys.path} (at the time +the module is loaded) for unrestricted code. +\end{memberdesc} + +\begin{memberdesc}{ok_posix_names} +% Should this be called ok_os_names? +Contains the names of the functions in the \refmodule{os} module which will be +available to programs running in the restricted environment. The +value for \class{RExec} is \code{('error', 'fstat', 'listdir', +'lstat', 'readlink', 'stat', 'times', 'uname', 'getpid', 'getppid', +'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid')}. +\end{memberdesc} + +\begin{memberdesc}{ok_sys_names} +Contains the names of the functions and variables in the \refmodule{sys} +module which will be available to programs running in the restricted +environment. The value for \class{RExec} is \code{('ps1', 'ps2', +'copyright', 'version', 'platform', 'exit', 'maxint')}. +\end{memberdesc} + + \subsection{An example} Let us say that we want a slightly more relaxed policy than the diff --git a/Doc/lib/librfc822.tex b/Doc/lib/librfc822.tex index 2f68bb8250..883d38cffb 100644 --- a/Doc/lib/librfc822.tex +++ b/Doc/lib/librfc822.tex @@ -82,7 +82,7 @@ usable. \begin{funcdesc}{mktime_tz}{tuple} Turn a 10-tuple as returned by \function{parsedate_tz()} into a UTC -timestamp. It the timezone item in the tuple is \code{None}, assume +timestamp. If the timezone item in the tuple is \code{None}, assume local time. Minor deficiency: this first interprets the first 8 elements as a local time and then compensates for the timezone difference; this may yield a slight error around daylight savings time @@ -211,13 +211,18 @@ there is no header matching \var{name}, or it is unparsable, return \code{None}. \end{methoddesc} -\class{Message} instances also support a read-only mapping interface. +\class{Message} instances also support a limited mapping interface. In particular: \code{\var{m}[name]} is like \code{\var{m}.getheader(name)} but raises \exception{KeyError} if there is no matching header; and \code{len(\var{m})}, \code{\var{m}.has_key(name)}, \code{\var{m}.keys()}, \code{\var{m}.values()} and \code{\var{m}.items()} act as expected -(and consistently). +(and consistently). \class{Message} instances also support the +mapping writable interface \code{\var{m}[name] = value} and \code{del +\var{m}[name]}. \class{Message} objects do not support the +\method{clear()}, \method{copy()}, \method{get()}, \method{popitem()}, +\method{setdefault()}, or \method{update()} methods of the mapping +interface. Finally, \class{Message} instances have two public instance variables: diff --git a/Doc/lib/libselect.tex b/Doc/lib/libselect.tex index b79f5c2d40..9113460f12 100644 --- a/Doc/lib/libselect.tex +++ b/Doc/lib/libselect.tex @@ -91,7 +91,7 @@ want to check for, and can be a combination of the constants described in the table below. If not specified, the default value used will check for all 3 types of events. -\begin{tableii}{l|l}{code}{Constant}{Meaning} +\begin{tableii}{l|l}{constant}{Constant}{Meaning} \lineii{POLLIN}{There is data to read} \lineii{POLLPRI}{There is urgent data to read} \lineii{POLLOUT}{Ready for output: writing will not block} @@ -126,6 +126,10 @@ with bits set for the reported events for that descriptor so forth. An empty list indicates that the call timed out and no file descriptors had any events to report. +If \var{timeout} is given, it specifies the length of time in +milliseconds which the system will wait for events before returning. +If \var{timeout} is omitted, negative, or \code{None}, the call will +block until there is an event for this poll object. \end{methoddesc} diff --git a/Doc/lib/libshlex.tex b/Doc/lib/libshlex.tex index 4ed928c95f..eecded7d8f 100644 --- a/Doc/lib/libshlex.tex +++ b/Doc/lib/libshlex.tex @@ -2,7 +2,7 @@ Simple lexical analysis} \declaremodule{standard}{shlex} -\modulesynopsis{Simple lexical analysis for \UNIX{} shell-like languages.} +\modulesynopsis{Simple lexical analysis for \UNIX\ shell-like languages.} \moduleauthor{Eric S. Raymond}{esr@snark.thyrsus.com} \sectionauthor{Eric S. Raymond}{esr@snark.thyrsus.com} diff --git a/Doc/lib/libsmtplib.tex b/Doc/lib/libsmtplib.tex index bc69387dd9..4a7b2dfdc8 100644 --- a/Doc/lib/libsmtplib.tex +++ b/Doc/lib/libsmtplib.tex @@ -241,17 +241,20 @@ import smtplib import string def prompt(prompt): - return string.strip(raw_input(prompt)) + return raw_input(prompt).strip() fromaddr = prompt("From: ") -toaddrs = string.split(prompt("To: ")) +toaddrs = prompt("To: ").split() print "Enter message, end with ^D:" # Add the From: and To: headers at the start! msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, string.join(toaddrs, ", "))) while 1: - line = raw_input() + try: + line = raw_input() + except EOFError: + break if not line: break msg = msg + line diff --git a/Doc/lib/libsocket.tex b/Doc/lib/libsocket.tex index 6598bf02c6..ac834fd7a2 100644 --- a/Doc/lib/libsocket.tex +++ b/Doc/lib/libsocket.tex @@ -114,7 +114,7 @@ returned. \begin{funcdesc}{gethostbyname}{hostname} Translate a host name to IP address format. The IP address is -returned as a string, e.g., \code{'100.50.200.5'}. If the host name +returned as a string, such as \code{'100.50.200.5'}. If the host name is an IP address itself it is returned unchanged. See \function{gethostbyname_ex()} for a more complete interface. \end{funcdesc} @@ -150,7 +150,7 @@ To find the fully qualified domain name, use the function \end{funcdesc} \begin{funcdesc}{getprotobyname}{protocolname} -Translate an Internet protocol name (e.g.\ \code{'icmp'}) to a constant +Translate an Internet protocol name (for example, \code{'icmp'}) to a constant suitable for passing as the (optional) third argument to the \function{socket()} function. This is usually only needed for sockets opened in ``raw'' mode (\constant{SOCK_RAW}); for the normal socket @@ -180,8 +180,9 @@ above. The file descriptor should refer to a socket, but this is not checked --- subsequent operations on the object may fail if the file descriptor is invalid. This function is rarely needed, but can be used to get or set socket options on a socket passed to a program as -standard input or output (e.g.\ a server started by the \UNIX{} inet +standard input or output (such as a server started by the \UNIX{} inet daemon). +Availability: \UNIX. \end{funcdesc} \begin{funcdesc}{ntohl}{x} @@ -209,8 +210,8 @@ no-op; otherwise, it performs a 2-byte swap operation. \end{funcdesc} \begin{funcdesc}{inet_aton}{ip_string} -Convert an IP address from dotted-quad string format -(e.g.\ '123.45.67.89') to 32-bit packed binary format, as a string four +Convert an IP address from dotted-quad string format (for example, +'123.45.67.89') to 32-bit packed binary format, as a string four characters in length. Useful when conversing with a program that uses the standard C library @@ -226,7 +227,7 @@ valid depends on the underlying C implementation of \begin{funcdesc}{inet_ntoa}{packed_ip} Convert a 32-bit packed IP address (a string four characters in length) to its standard dotted-quad string representation -(e.g. '123.45.67.89'). +(for example, '123.45.67.89'). Useful when conversing with a program that uses the standard C library and needs objects of type \ctype{struct in_addr}, which is the C type @@ -292,7 +293,7 @@ instead of raising an exception for errors returned by the C-level \cfunction{connect()} call (other problems, such as ``host not found,'' can still raise exceptions). The error indicator is \code{0} if the operation succeeded, otherwise the value of the \cdata{errno} -variable. This is useful, e.g., for asynchronous connects. +variable. This is useful to support, for example, asynchronous connects. \strong{Note:} This method has historically accepted a pair of parameters for \constant{AF_INET} addresses instead of only a tuple. This was never intentional and is no longer be available in Python @@ -344,7 +345,8 @@ socket file descriptor, so the file object and socket object may be closed or garbage-collected independently. \index{I/O control!buffering}The optional \var{mode} and \var{bufsize} arguments are interpreted the same way as by the -built-in \function{open()} function. +built-in \function{open()} function; see ``Built-in Functions'' +(section \ref{built-in-funcs}) for more information. \end{methoddesc} \begin{methoddesc}[socket]{recv}{bufsize\optional{, flags}} @@ -368,6 +370,19 @@ same meaning as for \method{recv()} above. Send data to the socket. The socket must be connected to a remote socket. The optional \var{flags} argument has the same meaning as for \method{recv()} above. Returns the number of bytes sent. +Applications are responsible for checking that all data has been sent; +if only some of the data was transmitted, the application needs to +attempt delivery of the remaining data. +\end{methoddesc} + +\begin{methoddesc}[socket]{sendall}{string\optional{, flags}} +Send data to the socket. The socket must be connected to a remote +socket. The optional \var{flags} argument has the same meaning as for +\method{recv()} above. Unlike \method{send()}, this method continues +to send data from \var{string} until either all data has been sent or +an error occurs. \code{None} is returned on success. On error, an +exception is raised, and there is no way to determine how much data, +if any, was successfully sent. \end{methoddesc} \begin{methoddesc}[socket]{sendto}{string\optional{, flags}, address} diff --git a/Doc/lib/libstdtypes.tex b/Doc/lib/libstdtypes.tex index 79221b8c46..cf7437da5c 100644 --- a/Doc/lib/libstdtypes.tex +++ b/Doc/lib/libstdtypes.tex @@ -1186,7 +1186,10 @@ Files have the following methods: \end{methoddesc} \begin{methoddesc}[file]{xreadlines}{} - Equivalent to \function{xreadlines.xreadlines(file)}.\refstmodindex{xreadlines} + Equivalent to + \function{xreadlines.xreadlines(\var{file})}.\refstmodindex{xreadlines} + (See the \refmodule{xreadlines} module for more information.) + \versionadded{2.1} \end{methoddesc} \begin{methoddesc}[file]{seek}{offset\optional{, whence}} @@ -1227,12 +1230,6 @@ Files have the following methods: \method{writelines()} does not add line separators.) \end{methoddesc} -\begin{methoddesc}[file]{xreadlines}{} - Equivalent to - \function{xreadlines.xreadlines(\var{file})}.\refstmodindex{xreadlines} - (See the \refmodule{xreadlines} module for more information.) -\end{methoddesc} - File objects also offer a number of other interesting attributes. These are not required for file-like objects, but should be diff --git a/Doc/lib/libstring.tex b/Doc/lib/libstring.tex index e95741eb8c..38a0dbd2cd 100644 --- a/Doc/lib/libstring.tex +++ b/Doc/lib/libstring.tex @@ -265,12 +265,3 @@ The functions defined in this module are: \var{maxsplit} is given, the first \var{maxsplit} occurrences are replaced. \end{funcdesc} - -This module is implemented in Python. Much of its functionality has -been reimplemented in the built-in module -\module{strop}\refbimodindex{strop}. However, you -should \emph{never} import the latter module directly. When -\module{string} discovers that \module{strop} exists, it transparently -replaces parts of itself with the implementation from \module{strop}. -After initialization, there is \emph{no} overhead in using -\module{string} instead of \module{strop}. diff --git a/Doc/lib/libsys.tex b/Doc/lib/libsys.tex index be5a599a45..ff5ee65f40 100644 --- a/Doc/lib/libsys.tex +++ b/Doc/lib/libsys.tex @@ -106,7 +106,7 @@ a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. Since most functions don't need access to the traceback, the best solution is to use something like -\code{type, value = sys.exc_info()[:2]} +\code{exctype, value = sys.exc_info()[:2]} to extract only the exception type and value. If you do need the traceback, make sure to delete it after use (best done with a \keyword{try} ... \keyword{finally} statement) or to call diff --git a/Doc/lib/libsyslog.tex b/Doc/lib/libsyslog.tex index 6f58287b26..fc59776c67 100644 --- a/Doc/lib/libsyslog.tex +++ b/Doc/lib/libsyslog.tex @@ -3,7 +3,7 @@ \declaremodule{builtin}{syslog} \platform{Unix} -\modulesynopsis{An interface to the \UNIX{} syslog library routines.} +\modulesynopsis{An interface to the \UNIX\ syslog library routines.} This module provides an interface to the \UNIX{} \code{syslog} library diff --git a/Doc/lib/libtermios.tex b/Doc/lib/libtermios.tex index 89481e6a63..f426f95eef 100644 --- a/Doc/lib/libtermios.tex +++ b/Doc/lib/libtermios.tex @@ -3,7 +3,7 @@ \declaremodule{builtin}{termios} \platform{Unix} -\modulesynopsis{\POSIX{} style tty control.} +\modulesynopsis{\POSIX\ style tty control.} \indexii{\POSIX{}}{I/O control} \indexii{tty}{I/O control} diff --git a/Doc/lib/libthreading.tex b/Doc/lib/libthreading.tex index eb0985f0b6..e3f07ba068 100644 --- a/Doc/lib/libthreading.tex +++ b/Doc/lib/libthreading.tex @@ -68,9 +68,9 @@ The \method{acquire()} method blocks if necessary until it can return without making the counter negative. \end{funcdesc} -\begin{classdesc}{Thread}{} +\begin{classdesc*}{Thread}{} A class that represents a thread of control. This class can be safely subclassed in a limited fashion. -\end{classdesc} +\end{classdesc*} Detailed interfaces for the objects are documented below. @@ -444,7 +444,7 @@ A thread can be flagged as a ``daemon thread''. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set with the \method{setDaemon()} -method and retrieved with the \method{getDaemon()} method. +method and retrieved with the \method{isDaemon()} method. There is a ``main thread'' object; this corresponds to the initial thread of control in the Python program. It is not a @@ -465,32 +465,28 @@ threads. This constructor should always be called with keyword arguments. Arguments are: -\var{group} -Should be \code{None}; reserved for future extension when a -\class{ThreadGroup} class is implemented. +\var{group} should be \code{None}; reserved for future extension when +a \class{ThreadGroup} class is implemented. -\var{target} -Callable object to be invoked by the \method{run()} method. -Defaults to \code{None}, meaning nothing is called. +\var{target} is the callable object to be invoked by the +\method{run()} method. Defaults to \code{None}, meaning nothing is +called. -\var{name} -The thread name. By default, a unique name is constructed of the form -``Thread-\var{N}'' where \var{N} is a small decimal number. +\var{name} is the thread name. By default, a unique name is +constructed of the form ``Thread-\var{N}'' where \var{N} is a small +decimal number. -\var{args} -Argument tuple for the target invocation. Defaults to \code{()}. +\var{args} is the argument tuple for the target invocation. Defaults +to \code{()}. -\var{kwargs} -Keyword argument dictionary for the target invocation. -Defaults to \code{\{\}}. +\var{kwargs} is a dictionary of keyword arguments for the target +invocation. Defaults to \code{\{\}}. If the subclass overrides the constructor, it must make sure to invoke the base class constructor (\code{Thread.__init__()}) before doing anything else to the thread. \end{classdesc} - - \begin{methoddesc}{start}{} Start the thread's activity. @@ -499,8 +495,6 @@ arranges for the object's \method{run()} method to be invoked in a separate thread of control. \end{methoddesc} - - \begin{methoddesc}{run}{} Method representing the thread's activity. @@ -511,7 +505,6 @@ arguments taken from the \var{args} and \var{kwargs} arguments, respectively. \end{methoddesc} - \begin{methoddesc}{join}{\optional{timeout}} Wait until the thread terminates. This blocks the calling thread until the thread whose \method{join()} @@ -531,8 +524,6 @@ It is an error to attempt to \method{join()} a thread before it has been started. \end{methoddesc} - - \begin{methoddesc}{getName}{} Return the thread's name. \end{methoddesc} @@ -565,4 +556,3 @@ The initial value is inherited from the creating thread. The entire Python program exits when no active non-daemon threads are left. \end{methoddesc} - diff --git a/Doc/lib/libtime.tex b/Doc/lib/libtime.tex index c3f62ed7bc..f8d5df2d18 100644 --- a/Doc/lib/libtime.tex +++ b/Doc/lib/libtime.tex @@ -122,14 +122,22 @@ or \function{localtime()} to a 24-character string of the following form: \code{'Sun Jun 20 23:21:05 1993'}. If \var{tuple} is not provided, the current time as returned by \function{localtime()} is used. Note: unlike the C function of the same name, there is no trailing newline. +\versionchanged[Allowed \var{tuple} to be omitted]{2.1} \end{funcdesc} \begin{funcdesc}{clock}{} -Return the current CPU time as a floating point number expressed in +On \UNIX, return +the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning -of ``CPU time''\index{CPU time}, depends on that of the C function -of the same name, but in any case, this is the function to use for -benchmarking\index{benchmarking} Python or timing algorithms. +of ``processor time''\index{CPU time}\index{processor time}, depends +on that of the C function of the same name, but in any case, this is +the function to use for benchmarking\index{benchmarking} Python or +timing algorithms. + +On Windows, this function returns the nearest approximation to +wall-clock time since the first call to this function, based on the +Win32 function \cfunction{QueryPerformanceCounter()}. The resolution +is typically better than one microsecond. \end{funcdesc} \begin{funcdesc}{ctime}{\optional{secs}} @@ -137,6 +145,7 @@ Convert a time expressed in seconds since the epoch to a string representing local time. If \var{secs} is not provided, the current time as returned by \function{time()} is used. \code{ctime(\var{secs})} is equivalent to \code{asctime(localtime(\var{secs}))}. +\versionchanged[Allowed \var{secs} to be omitted]{2.1} \end{funcdesc} \begin{datadesc}{daylight} @@ -149,11 +158,13 @@ in UTC in which the dst flag is always zero. If \var{secs} is not provided, the current time as returned by \function{time()} is used. Fractions of a second are ignored. See above for a description of the tuple lay-out. +\versionchanged[Allowed \var{secs} to be omitted]{2.1} \end{funcdesc} \begin{funcdesc}{localtime}{\optional{secs}} Like \function{gmtime()} but converts to local time. The dst flag is set to \code{1} when DST applies to the given time. +\versionchanged[Allowed \var{secs} to be omitted]{2.1} \end{funcdesc} \begin{funcdesc}{mktime}{tuple} @@ -180,6 +191,7 @@ Convert a tuple representing a time as returned by \function{gmtime()} or \function{localtime()} to a string as specified by the \var{format} argument. If \var{tuple} is not provided, the current time as returned by \function{localtime()} is used. \var{format} must be a string. +\versionchanged[Allowed \var{tuple} to be omitted]{2.1} The following directives can be embedded in the \var{format} string. They are shown without the optional field width and precision @@ -225,19 +237,19 @@ Notes: \end{description} Here is an example, a format for dates compatible with that specified -in the \rfc{822} Internet email standard. - \footnote{The use of \%Z is now - deprecated, but the \%z escape that expands to the preferred +in the \rfc{2822} Internet email standard. + \footnote{The use of \code{\%Z} is now + deprecated, but the \code{\%z} escape that expands to the preferred hour/minute offset is not supported by all ANSI C libraries. Also, a strict reading of the original 1982 \rfc{822} standard calls for a two-digit year (\%y rather than \%Y), but practice moved to - 4-digit years long before the year 2000.} + 4-digit years long before the year 2000. The 4-digit year has + been mandated by \rfc{2822}, which obsoletes \rfc{822}.} \begin{verbatim} ->>> from time import * ->>> strftime("%a, %d %b %Y %H:%M:%S %Z", localtime()) -'Sat, 27 Jan 2001 05:15:05 EST' ->>> +>>> from time import gmtime, strftime +>>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) +'Thu, 28 Jun 2001 14:17:15 +0000' \end{verbatim} Additional directives may be supported on certain platforms, but diff --git a/Doc/lib/libweakref.tex b/Doc/lib/libweakref.tex index 5e6e81933f..9062816d2d 100644 --- a/Doc/lib/libweakref.tex +++ b/Doc/lib/libweakref.tex @@ -5,7 +5,7 @@ \modulesynopsis{Support for weak references and weak dictionaries.} \moduleauthor{Fred L. Drake, Jr.}{fdrake@acm.org} \moduleauthor{Neil Schemenauer}{nas@arctrix.com} -\moduleauthor{Martin von L\o"wis}{martin@loewis.home.cs.tu-berlin.de} +\moduleauthor{Martin von L\"owis}{martin@loewis.home.cs.tu-berlin.de} \sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org} \versionadded{2.1} @@ -62,7 +62,7 @@ be made to support weak references; see section \ref{weakref-extension}, callable. Proxy objects are not hashable regardless of the referent; this avoids a number of problems related to their fundamentally mutable nature, and prevent their use as dictionary - keys. \var{callable} is the same as the parameter of the same name + keys. \var{callback} is the same as the parameter of the same name to the \function{ref()} function. \end{funcdesc} @@ -226,28 +226,26 @@ PyTypeObject PyInstance_Type = { 0, "instance", - /* lots of stuff omitted for brevity */ + /* Lots of stuff omitted for brevity... */ offsetof(PyInstanceObject, in_weakreflist) /* tp_weaklistoffset */ }; \end{verbatim} The only further addition is that the destructor needs to call the -weak reference manager to clear any weak references and return if the -object has been resurrected. This needs to occur before any other -parts of the destruction have occurred: +weak reference manager to clear any weak references. This should be +done before any other parts of the destruction have occurred: \begin{verbatim} static void instance_dealloc(PyInstanceObject *inst) { - /* allocate tempories if needed, but do not begin - destruction here + /* Allocate tempories if needed, but do not begin + destruction just yet. */ - if (!PyObject_ClearWeakRefs((PyObject *) inst)) - return; + PyObject_ClearWeakRefs((PyObject *) inst); - /* proceed with object destuction normally */ + /* Proceed with object destuction normally. */ } \end{verbatim} diff --git a/Doc/lib/libwebbrowser.tex b/Doc/lib/libwebbrowser.tex index ddcfa5fe06..285fcf5582 100644 --- a/Doc/lib/libwebbrowser.tex +++ b/Doc/lib/libwebbrowser.tex @@ -48,8 +48,7 @@ The following functions are defined: \begin{funcdesc}{open_new}{url} Open \var{url} in a new window of the default browser, if possible, - otherwise, open \var{url} in the only browser window. (This entry - point is deprecated and may be removed in 2.1.) + otherwise, open \var{url} in the only browser window. \end{funcdesc} \begin{funcdesc}{get}{\optional{name}} @@ -125,6 +124,5 @@ module-level convenience functions: \begin{funcdesc}{open_new}{url} Open \var{url} in a new window of the browser handled by this controller, if possible, otherwise, open \var{url} in the only - browser window. (This method is deprecated and may be removed in - 2.1.) + browser window. \end{funcdesc} diff --git a/Doc/lib/libzipfile.tex b/Doc/lib/libzipfile.tex index 2f2f562d57..628dfe5ca3 100644 --- a/Doc/lib/libzipfile.tex +++ b/Doc/lib/libzipfile.tex @@ -77,13 +77,14 @@ The available attributes of this module are: \subsection{ZipFile Objects \label{zipfile-objects}} -\begin{classdesc}{ZipFile}{filename\optional{, mode\optional{, compression}}} - Open a ZIP file named \var{filename}. The \var{mode} parameter +\begin{classdesc}{ZipFile}{file\optional{, mode\optional{, compression}}} + Open a ZIP file, where \var{file} can be either a path to a file + (i.e. a string) or a file-like object. The \var{mode} parameter should be \code{'r'} to read an existing file, \code{'w'} to truncate and write a new file, or \code{'a'} to append to an - existing file. For \var{mode} is \code{'a'} and \var{filename} + existing file. For \var{mode} is \code{'a'} and \var{file} refers to an existing ZIP file, then additional files are added to - it. If \var{filename} does not refer to a ZIP file, then a new ZIP + it. If \var{file} does not refer to a ZIP file, then a new ZIP archive is appended to the file. This is meant for adding a ZIP archive to another file, such as \file{python.exe}. Using @@ -96,7 +97,7 @@ cat myzip.zip >> python.exe the archive, and should be \constant{ZIP_STORED} or \constant{ZIP_DEFLATED}; unrecognized values will cause \exception{RuntimeError} to be raised. If \constant{ZIP_DEFLATED} - is specified but the \refmodule{zlib} module is not avaialble, + is specified but the \refmodule{zlib} module is not available, \exception{RuntimeError} is also raised. The default is \constant{ZIP_STORED}. \end{classdesc} diff --git a/Doc/lib/libzlib.tex b/Doc/lib/libzlib.tex index 1da7f78352..c78523b1ff 100644 --- a/Doc/lib/libzlib.tex +++ b/Doc/lib/libzlib.tex @@ -9,7 +9,7 @@ For applications that require data compression, the functions in this module allow compression and decompression, using the zlib library. The zlib library has its own home page at -\url{http://www.info-zip.org/pub/infozip/zlib/}. Version 1.1.3 is the +\url{http://www.gzip.org/zlib/}. Version 1.1.3 is the most recent version as of September 2000; use a later version if one is available. There are known incompatibilities between the Python module and earlier versions of the zlib library. @@ -87,7 +87,7 @@ default size is 16384. \end{funcdesc} \begin{funcdesc}{decompressobj}{\optional{wbits}} - Returns a compression object, to be used for decompressing data + Returns a decompression object, to be used for decompressing data streams that won't fit into memory at once. The \var{wbits} parameter controls the size of the window buffer. \end{funcdesc} @@ -149,6 +149,5 @@ action is to delete the object. \begin{seealso} \seemodule{gzip}{Reading and writing \program{gzip}-format files.} - \seeurl{http://www.info-zip.org/pub/infozip/zlib/}{The - zlib library home page.} + \seeurl{http://www.gzip.org/zlib/}{The zlib library home page.} \end{seealso} diff --git a/Doc/lib/xmldom.tex b/Doc/lib/xmldom.tex index 5d4fe024e8..bb47895d80 100644 --- a/Doc/lib/xmldom.tex +++ b/Doc/lib/xmldom.tex @@ -193,7 +193,7 @@ This is a read-only attribute. \end{memberdesc} \begin{memberdesc}[Node]{attributes} -A \class{NamedNodeList} of attribute objects. Only elements have +A \class{NamedNodeMap} of attribute objects. Only elements have actual values for this; others provide \code{None} for this attribute. This is a read-only attribute. \end{memberdesc} diff --git a/Doc/libmods.tex b/Doc/libmods.tex deleted file mode 100755 index 5bc6ee21e3..0000000000 --- a/Doc/libmods.tex +++ /dev/null @@ -1,7 +0,0 @@ -\chapter{Built-in Modules} - -The modules described in this chapter are built into the interpreter -and considered part of Python's standard environment: they are always -available.\footnote{at least in theory --- it is possible to specify -at build time that one or more of these modules should be excluded, -but it would be antisocial to do so.} diff --git a/Doc/libstd.tex b/Doc/libstd.tex deleted file mode 100755 index e642a8d60b..0000000000 --- a/Doc/libstd.tex +++ /dev/null @@ -1,7 +0,0 @@ -\chapter{Standard Modules} - -The modules described in this chapter are implemented in Python, but -are considered to be a part of Python's standard environment: they are -always available.\footnote{at least in theory --- it is possible to -botch the library installation or to sabotage the module search path -so that these modules cannot be found.} diff --git a/Doc/mac/libcolorpicker.tex b/Doc/mac/libcolorpicker.tex index c94fdf863a..596e9c2e27 100644 --- a/Doc/mac/libcolorpicker.tex +++ b/Doc/mac/libcolorpicker.tex @@ -3,7 +3,7 @@ \declaremodule{extension}{ColorPicker} \platform{Mac} -\modulesynopsis{} +\modulesynopsis{Interface to the standard color selection dialog.} \moduleauthor{Just van Rossum}{just@letterror.com} \sectionauthor{Fred L. Drake, Jr.}{fdrake@acm.org} diff --git a/Doc/mac/libmacui.tex b/Doc/mac/libmacui.tex index 053176e537..62f9b5705a 100644 --- a/Doc/mac/libmacui.tex +++ b/Doc/mac/libmacui.tex @@ -45,7 +45,8 @@ hitting return is \code{0}. This can be changed with the optional \var{default} argument. \end{funcdesc} -\begin{funcdesc}{ProgressBar}{\optional{title \optional{, maxval\optional{,label}}}} +\begin{funcdesc}{ProgressBar}{\optional{title\optional{, maxval\optional{, + label}}}} Display a modeless progress dialog with a thermometer bar. \var{title} is the text string displayed (default ``Working...''), \var{maxval} is the value at which progress is complete (default @@ -58,3 +59,48 @@ remains visible until the object returned is discarded. The progress bar has a ``cancel'' button. [NOTE: how does the cancel button behave?] \end{funcdesc} + + +\begin{funcdesc}{GetArgv}{\optional{optionlist\optional{ + commandlist\optional{, addoldfile\optional{, addnewfile\optional{, + addfolder\optional{, id}}}}}}} +Displays a dialog which aids the user in constructing a command-line +argument list. Returns the list in \code{sys.argv} format, suitable for +passing as an argument to \function{getopt.getopt()}. \var{addoldfile}, +\var{addnewfile}, and \var{addfolder} are boolean arguments. When +nonzero, they enable the user to insert into the command line paths to +an existing file, a (possibly) not-yet-existent file, and a folder, +respectively. (Note: Option arguments must appear in the command line +before file and folder arguments in order to be recognized by +\function{getopt.getopt()}.) Arguments containing spaces can be +specified by enclosing them within single or double quotes. A +\exception{SystemExit} exception is raised if the user presses the +``Cancel'' button. + +\var{optionlist} is a list that determines a popup menu from which the +allowed options are selected. Its items can take one of two forms: +\var{optstr} or \code{(\var{optstr}, \var{descr})}. When present, +\var{descr} is a short descriptive string that is displayed in the +dialog while this option is selected in the popup menu. The +correspondence between \var{optstr}s and command-line arguments is: + +\begin{tableii}{l|l}{textrm}{\var{optstr} format}{Command-line format} +\lineii{\code{x}} + {\programopt{-x} (short option)} +\lineii{\code{x:} or \code{x=}} + {\programopt{-x} (short option with value)} +\lineii{\code{xyz}} + {\longprogramopt{xyz} (long option)} +\lineii{\code{xyz:} or \code{xyz=}} + {\longprogramopt{xyz} (long option with value)} +\end{tableii} + +\var{commandlist} is a list of items of the form \var{cmdstr} or +\code{(\var{cmdstr}, \var{descr})}, where \var{descr} is as above. The +\var{cmdstr}s will appear in a popup menu. When chosen, the text of +\var{cmdstr} will be appended to the command line as is, except that a +trailing \character{:} or \character{=} (if present) will be trimmed +off. + +\versionadded{2.0} +\end{funcdesc} diff --git a/Doc/mac/mac.tex b/Doc/mac/mac.tex index 2edd8573e0..dab638380f 100644 --- a/Doc/mac/mac.tex +++ b/Doc/mac/mac.tex @@ -71,6 +71,10 @@ documented here: \input{undoc} % Undocumented Modules +\appendix +\chapter{History and License} +\input{license} + % % The ugly "%begin{latexonly}" pseudo-environments are really just to % keep LaTeX2HTML quiet during the \renewcommand{} macros; they're diff --git a/Doc/mac/toolbox.tex b/Doc/mac/toolbox.tex index d497d0badf..9f48566a24 100644 --- a/Doc/mac/toolbox.tex +++ b/Doc/mac/toolbox.tex @@ -93,7 +93,15 @@ in touch with \email{python-docs@python.org}. \section{\module{Scrap} --- Scrap Manager} \declaremodule{standard}{Scrap} \platform{Mac} -\modulesynopsis{Interface to the Scrap Manager} +\modulesynopsis{The Scrap Manager provides basic services for + implementing cut \&\ paste and clipboard operations.} + +\begin{seealso} + \seetitle[http://developer.apple.com/techpubs/mac/MoreToolbox/MoreToolbox-109.html]{Scrap + Manager}{Apple's documentation for the Scrap Manager gives + a lot of useful information about using the Scrap Manager + in applications.} +\end{seealso} \section{\module{Snd} --- Sound Manager} diff --git a/Doc/mac/undoc.tex b/Doc/mac/undoc.tex index 0406fcfc07..d33fbda02b 100644 --- a/Doc/mac/undoc.tex +++ b/Doc/mac/undoc.tex @@ -11,13 +11,19 @@ touch with \email{python-docs@python.org}. \section{\module{buildtools} --- Helper module for BuildApplet and Friends} \declaremodule{standard}{buildtools} \platform{Mac} -\modulesynopsis{Helper module for BuildApplet, BuildApplication and macfreeze} +\modulesynopsis{Helper module for BuildApplet, BuildApplication and + macfreeze} -\section{\module{py_resource} --- } +\section{\module{py_resource} --- Resources from Python code} \declaremodule[pyresource]{standard}{py_resource} \platform{Mac} -\modulesynopsis{} +\modulesynopsis{Helper to create \texttt{'PYC '} resources for compiled + applications} + +This module is primarily used as a help module for BuildApplet and +BuildApplication. It is able to store compiled Python code as +\texttt{'PYC '} resources in a file. \section{\module{cfmfile} --- Code Fragment Resource module} @@ -61,10 +67,10 @@ with a version that uses Internet Config to set file type and creator for new files. -\section{\module{mactty} --- } +\section{\module{mactty} --- Serial line connections} \declaremodule{standard}{mactty} \platform{Mac} -\modulesynopsis{} +\modulesynopsis{Easy access serial to line connections} \section{\module{nsremote} --- Wrapper around Netscape OSA modules} @@ -89,16 +95,27 @@ allows access to the fields by name. It also has methods to convert to and from \module{PIL} images. -\section{\module{preferences} --- } +\section{\module{preferences} --- Application preferences manager} \declaremodule{standard}{preferences} \platform{Mac} -\modulesynopsis{} +\modulesynopsis{Nice application preferences manager with support for + defaults} + +The \module{preferences} module allows storage of user preferences in +the system-wide preferences folder, with defaults coming from the +application itself and the possibility to override preferences for +specific situations. -\section{\module{pythonprefs} --- } +\section{\module{pythonprefs} --- Preferences manager for Python} \declaremodule{standard}{pythonprefs} \platform{Mac} -\modulesynopsis{} +\modulesynopsis{Specialized preferences manager for the Python + interpreter} + +This module is a specialization of the \refmodule{preferences} module +that allows reading and writing of the preferences for the Python +interpreter. \section{\module{quietconsole} --- non-visible stdout output} diff --git a/Doc/mac/using.tex b/Doc/mac/using.tex index 0a077b9db1..47df26e999 100644 --- a/Doc/mac/using.tex +++ b/Doc/mac/using.tex @@ -207,7 +207,7 @@ a class browser, a graphical debugger, and more. Use this window like you would the \program{PythonInterpreter}, except that you cannot use the ``Drag and drop'' method above. Instead, dropping a script onto the \program{Python IDE} icon will open the -file in a seperate script window (which you can then execute manually +file in a separate script window (which you can then execute manually -- see section \ref{IDEexecution}). @@ -262,7 +262,7 @@ saving it as an ``applet'' (by selecting ``Save as applet'' from the files or folders onto it, to pass them to the applet the way command-line users would type them onto the command-line to pass them as arguments to the script. However, you should make sure to save the -applet as a seperate file, do not overwrite the script you are +applet as a separate file, do not overwrite the script you are writing, because you will not be able to edit it again. Accessing the items passed to the applet via ``drag-and-drop'' is done diff --git a/Doc/perl/l2hinit.perl b/Doc/perl/l2hinit.perl index d3720d9997..7ef9ad63d9 100644 --- a/Doc/perl/l2hinit.perl +++ b/Doc/perl/l2hinit.perl @@ -181,12 +181,12 @@ sub make_nav_panel { sub get_version_text { if ($PACKAGE_VERSION ne '' && $t_date) { return ("" - . "Release $PACKAGE_VERSION," + . "Release $PACKAGE_VERSION$RELEASE_INFO," . " documentation updated on $t_date."); } if ($PACKAGE_VERSION ne '') { return ("" - . "Release $PACKAGE_VERSION."); + . "Release $PACKAGE_VERSION$RELEASE_INFO."); } if ($t_date) { return ("Documentation released on " @@ -415,7 +415,7 @@ sub do_cmd_textohtmlinfopage { if ($t_date) { # mostly ours $the_version = ",\n$t_date"; if ($PACKAGE_VERSION) { - $the_version .= ", Release $PACKAGE_VERSION"; + $the_version .= ", Release $PACKAGE_VERSION$RELEASE_INFO"; } } $_ = (($INFO == 1) diff --git a/Doc/perl/python.perl b/Doc/perl/python.perl index 20615ccd9a..1e54ae9f9d 100644 --- a/Doc/perl/python.perl +++ b/Doc/perl/python.perl @@ -86,6 +86,7 @@ sub do_cmd_let{ # the older version of LaTeX2HTML we use doesn't support this, but we use it: sub do_cmd_textasciitilde{ '~' . @_[0]; } +sub do_cmd_textasciicircum{ '^' . @_[0]; } # words typeset in a special way (not in HTML though) @@ -103,6 +104,7 @@ sub do_cmd_e{ '\' . @_[0]; } $DEVELOPER_ADDRESS = ''; $SHORT_VERSION = ''; +$RELEASE_INFO = ''; $PACKAGE_VERSION = ''; sub do_cmd_version{ $PACKAGE_VERSION . @_[0]; } @@ -113,6 +115,12 @@ sub do_cmd_release{ return $_; } +sub do_cmd_setreleaseinfo{ + local($_) = @_; + $RELEASE_INFO = next_argument(); + return $_; +} + sub do_cmd_setshortversion{ local($_) = @_; $SHORT_VERSION = next_argument(); @@ -344,26 +352,27 @@ sub do_cmd_deprecated{ . $_); } -sub do_cmd_versionadded{ - # one parameter: \versionadded{version} - local($_) = @_; - my $release = next_argument(); - return ("\nNew in version $release.\n" - . $_); -} - -sub do_cmd_versionchanged{ - # one parameter: \versionchanged{version} - local($_) = @_; +sub versionnote{ + # one or two parameters: \versionnote[explanation]{version} + my $type = @_[0]; + local $_ = @_[1]; my $explanation = next_optional_argument(); my $release = next_argument(); - my $text = "Changed in version $release."; + my $text = "$type in version $release."; if ($explanation) { - $text = "Changed in version $release:\n$explanation."; + $text = "$type in version $release:\n$explanation."; } return "\n$text\n" . $_; } +sub do_cmd_versionadded{ + return versionnote('New', @_); +} + +sub do_cmd_versionchanged{ + return versionnote('Changed', @_); +} + # # These function handle platform dependency tracking. # @@ -904,6 +913,17 @@ sub do_env_classdesc{ return handle_classlike_descriptor(@_[0], "class"); } +sub do_env_classdescstar{ + local($_) = @_; + $THIS_CLASS = next_argument(); + $idx = make_str_index_entry( + "$THIS_CLASS (class in $THIS_MODULE)"); + $idx =~ s/ \(.*\)//; + return ("
class $idx\n
" + . $_ + . '
'); +} + sub do_env_excclassdesc{ return handle_classlike_descriptor(@_[0], "exception"); } @@ -1294,7 +1314,8 @@ sub make_my_titlepage() { if ($t_date) { $the_title .= "\n

"; if ($PACKAGE_VERSION) { - $the_title .= "Release $PACKAGE_VERSION
\n"; + $the_title .= ('Release ' + . "$PACKAGE_VERSION$RELEASE_INFO
\n"); } $the_title .= "$t_date

" } diff --git a/Doc/ref/ref.tex b/Doc/ref/ref.tex index 0f65ddba1a..8259b80c41 100644 --- a/Doc/ref/ref.tex +++ b/Doc/ref/ref.tex @@ -61,6 +61,10 @@ C/\Cpp{} programmers in detail. \appendix \input{refa1} % Future statements and nested scopes +\appendix +\chapter{History and License} +\input{license} + \input{ref.ind} \end{document} diff --git a/Doc/ref/ref3.tex b/Doc/ref/ref3.tex index 1f3afbf357..a82ce8cc7d 100644 --- a/Doc/ref/ref3.tex +++ b/Doc/ref/ref3.tex @@ -159,7 +159,8 @@ numbers are of course strongly related to mathematical numbers, but subject to the limitations of numerical representation in computers. \obindex{numeric} -Python distinguishes between integers and floating point numbers: +Python distinguishes between integers, floating point numbers, and +complex numbers: \begin{description} \item[Integers] @@ -1009,10 +1010,14 @@ implement the operation for a given pair of arguments. \begin{methoddesc}[object]{__cmp__}{self, other} Called by comparison operations if rich comparison (see above) is not -defined. Should return a negative integer if -\code{self < other}, zero if \code{self == other}, a positive integer if -\code{self > other}. If no \method{__cmp__()} operation is defined, class -instances are compared by object identity (``address''). +defined. Should return a negative integer if \code{self < other}, +zero if \code{self == other}, a positive integer if \code{self > +other}. If no \method{__cmp__()}, \method{__eq__()} or +\method{__ne__()} operation is defined, class instances are compared +by object identity (``address''). See also the description of +\method{__hash__()} for some important notes on creating objects which +support custom comparison operations and are usable as dictionary +keys. (Note: the restriction that exceptions are not propagated by \method{__cmp__()} has been removed in Python 1.5.) \bifuncindex{cmp} @@ -1034,12 +1039,13 @@ mix together (e.g., using exclusive or) the hash values for the components of the object that also play a part in comparison of objects. If a class does not define a \method{__cmp__()} method it should not define a \method{__hash__()} operation either; if it defines -\method{__cmp__()} but not \method{__hash__()} its instances will not be -usable as dictionary keys. If a class defines mutable objects and -implements a \method{__cmp__()} method it should not implement -\method{__hash__()}, since the dictionary implementation requires that -a key's hash value is immutable (if the object's hash value changes, it -will be in the wrong hash bucket). +\method{__cmp__()} or \method{__eq__()} but not \method{__hash__()}, +its instances will not be usable as dictionary keys. If a class +defines mutable objects and implements a \method{__cmp__()} or +\method{__eq__()} method, it should not implement \method{__hash__()}, +since the dictionary implementation requires that a key's hash value +is immutable (if the object's hash value changes, it will be in the +wrong hash bucket). \withsubitem{(object method)}{\ttindex{__cmp__()}} \end{methoddesc} @@ -1134,7 +1140,10 @@ multiplication (meaning repetition) by defining the methods \method{__add__()}, \method{__radd__()}, \method{__iadd__()}, \method{__mul__()}, \method{__rmul__()} and \method{__imul__()} described below; they should not define \method{__coerce__()} or other numerical -operators. +operators. It is recommended that both mappings and sequences +implement the \method{__contains__}, to allow efficient use of the +\code{in} operator; for mappings, \code{in} should be equivalent of +\method{has_key()}; for sequences, it should search through the values. \withsubitem{(mapping object method)}{ \ttindex{keys()} \ttindex{values()} @@ -1143,7 +1152,8 @@ operators. \ttindex{get()} \ttindex{clear()} \ttindex{copy()} - \ttindex{update()}} + \ttindex{update()} + \ttindex{__contains__()}} \withsubitem{(sequence object method)}{ \ttindex{append()} \ttindex{count()} @@ -1158,7 +1168,8 @@ operators. \ttindex{__iadd__()} \ttindex{__mul__()} \ttindex{__rmul__()} - \ttindex{__imul__()}} + \ttindex{__imul__()} + \ttindex{__contains__()}} \withsubitem{(numeric object method)}{\ttindex{__coerce__()}} \begin{methoddesc}[mapping object]{__len__}{self} diff --git a/Doc/ref/ref4.tex b/Doc/ref/ref4.tex index 636bc1d375..754a5b59d0 100644 --- a/Doc/ref/ref4.tex +++ b/Doc/ref/ref4.tex @@ -80,7 +80,7 @@ searched in the built-in namespace (which is actually the global namespace of the module \module{__builtin__}\refbimodindex{__builtin__}). The built-in namespace associated with the execution of a code block is actually -found by looking up the name \code{__builtins__} is its global +found by looking up the name \code{__builtins__} in its global namespace; this should be a dictionary or a module (in the latter case its dictionary is used). Normally, the \code{__builtins__} namespace is the dictionary of the built-in module \module{__builtin__} (note: diff --git a/Doc/ref/ref5.tex b/Doc/ref/ref5.tex index 5663daaef2..b9eaad2464 100644 --- a/Doc/ref/ref5.tex +++ b/Doc/ref/ref5.tex @@ -867,17 +867,31 @@ that functions created with lambda forms cannot contain statements. \indexii{lambda}{form} \indexii{anonmymous}{function} -\strong{Programmer's note:} a lambda form defined inside a function -has no access to names defined in the function's namespace. This is -because Python has only two scopes: local and global. A common -work-around is to use default argument values to pass selected -variables into the lambda's namespace, e.g.: +\strong{Programmer's note:} Prior to Python 2.1, a lambda form defined +inside a function has no access to names defined in the function's +namespace. This is because Python had only two scopes: local and +global. A common work-around was to use default argument values to +pass selected variables into the lambda's namespace, e.g.: \begin{verbatim} def make_incrementor(increment): return lambda x, n=increment: x+n \end{verbatim} +Python 2.1 introduced nested scopes as an optional feature, and this +work-around has not been necessary when the feature is enabled. The +use of nested scopes is enabled by the statement \samp{from __future__ +import nested_scopes}; future versions of Python will enable nested +scopes by default. This version works starting with Python 2.1: + +\begin{verbatim} +from __future__ import nested_scopes + +def make_incrementor(increment): + return lambda x: x+increment +\end{verbatim} + + \section{Expression lists\label{exprlists}} \indexii{expression}{list} @@ -938,11 +952,11 @@ left). \lineii{\code{*}, \code{/}, \code{\%}} {Multiplication, division, remainder} \hline - \lineii{\code{**}} {Exponentiation} - \hline \lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative} \lineii{\code{\~\var{x}}} {Bitwise not} \hline + \lineii{\code{**}} {Exponentiation} + \hline \lineii{\code{\var{x}.\var{attribute}}} {Attribute reference} \lineii{\code{\var{x}[\var{index}]}} {Subscription} \lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing} diff --git a/Doc/ref/ref6.tex b/Doc/ref/ref6.tex index f90317f140..030b2433da 100644 --- a/Doc/ref/ref6.tex +++ b/Doc/ref/ref6.tex @@ -566,11 +566,20 @@ list of identifiers, looks each one of them up in the module found in step As with the first form of \keyword{import}, an alternate local name can be supplied by specifying "\keyword{as} localname". If a name is not found, \exception{ImportError} is raised. If the list of identifiers is replaced -by a star (\samp{*}), all names defined in the module are bound, except -those beginning with an underscore (\character{_}). +by a star (\character{*}), all public names defined in the module are +bound in the local namespace of the \keyword{import} statement.. \indexii{name}{binding} \exindex{ImportError} +The \emph{public names} defined by a module are determined by checking +the module's namespace for a variable named \code{__all__}; if +defined, it must be a sequence of strings which are names defined or +imported by that module. The names given in \code{__all__} are all +considered public and are required to exist. If \code{__all__} is not +defined, the set of public names includes all names found in the +module's namespace which do not begin with an underscore character +(\character{_}). + Names bound by \keyword{import} statements may not occur in \keyword{global} statements in the same scope. \stindex{global} @@ -591,7 +600,11 @@ file \file{__init__.py}.\ttindex{__init__.py} \url{http://www.python.org/doc/essays/packages.html} for more details, also about how the module search works from inside a package.] -[XXX Also should mention __import__().] +The built-in function \function{__import__()} is provided to support +applications that determine which modules need to be loaded +dynamically; refer to ``Built-in Functions'' in the +\citetitle[../lib/lib.html]{Python Library Reference} for additional +information. \bifuncindex{__import__} \section{The \keyword{global} statement \label{global}} diff --git a/Doc/ref/ref7.tex b/Doc/ref/ref7.tex index 9107fe9ca9..ec0972e7cc 100644 --- a/Doc/ref/ref7.tex +++ b/Doc/ref/ref7.tex @@ -280,6 +280,7 @@ restriction may be lifted in the future). \section{Function definitions\label{function}} \indexii{function}{definition} +\stindex{def} A function definition defines a user-defined function object (see section \ref{types}): @@ -370,6 +371,7 @@ description of the new semantics. \section{Class definitions\label{class}} \indexii{class}{definition} +\stindex{class} A class definition defines a class object (see section \ref{types}): \obindex{class} @@ -401,6 +403,6 @@ are class variables; they are shared by all instances. To define instance variables, they must be given a value in the the \method{__init__()} method or in another method. Both class and instance variables are accessible through the notation -```code{self.name}'', and an instance variable hides a class variable +``\code{self.name}'', and an instance variable hides a class variable with the same name when accessed in this way. Class variables with immutable values can be used as defaults for instance variables. diff --git a/Doc/templates/howto.tex b/Doc/templates/howto.tex index fcb213a9d5..1f7bb6fccc 100644 --- a/Doc/templates/howto.tex +++ b/Doc/templates/howto.tex @@ -1,3 +1,10 @@ +% Complete documentation on the extended LaTeX markup used for Python +% documentation is available in ``Documenting Python'', which is part +% of the standard documentation for Python. It may be found online +% at: +% +% http://www.python.org/doc/current/doc/doc.html + \documentclass{howto} % This is a template for short or medium-size Python-related documents, diff --git a/Doc/templates/manual.tex b/Doc/templates/manual.tex index a8c8ec2109..e1114d67e2 100644 --- a/Doc/templates/manual.tex +++ b/Doc/templates/manual.tex @@ -1,3 +1,10 @@ +% Complete documentation on the extended LaTeX markup used for Python +% documentation is available in ``Documenting Python'', which is part +% of the standard documentation for Python. It may be found online +% at: +% +% http://www.python.org/doc/current/doc/doc.html + \documentclass{manual} \title{Big Python Manual} diff --git a/Doc/templates/module.tex b/Doc/templates/module.tex index 33d769d799..1a0117d64e 100644 --- a/Doc/templates/module.tex +++ b/Doc/templates/module.tex @@ -1,5 +1,12 @@ % Template for a library manual section. % PLEASE REMOVE THE COMMENTS AFTER USING THE TEMPLATE +% +% Complete documentation on the extended LaTeX markup used for Python +% documentation is available in ``Documenting Python'', which is part +% of the standard documentation for Python. It may be found online +% at: +% +% http://www.python.org/doc/current/doc/doc.html % ==== 0. ==== % Copy this file to /lib.tex, and edit that file @@ -13,7 +20,7 @@ % appropriate. \section{\module{spam} --- - Short descrition, for section title} + Short description, for section title and table of contents} % Choose one of these to specify the module module name. If there's % an underscore in the name, use @@ -31,9 +38,9 @@ % Please use a name that has already been used whenever applicable. If this % is omitted, no availability statement is produced or implied. % -% \platform{UNIX} +% \platform{Unix} -% These apply to all modules: +% These apply to all modules, and may be given more than once: \moduleauthor{name}{email} % Author of the module code; % omit if not known. diff --git a/Doc/texinputs/boilerplate.tex b/Doc/texinputs/boilerplate.tex index e296dbd957..1f74b1f1e8 100644 --- a/Doc/texinputs/boilerplate.tex +++ b/Doc/texinputs/boilerplate.tex @@ -5,6 +5,7 @@ E-mail: \email{python-docs@python.org} } -\date{April 15, 2001} % XXX update before release! -\release{2.1} % software release, not documentation +\date{January 16, 2002} % XXX update before release! +\release{2.1.2} % software release, not documentation +\setreleaseinfo{} % empty for final release \setshortversion{2.1} % major.minor only for software diff --git a/Doc/texinputs/copyright.tex b/Doc/texinputs/copyright.tex dissimilarity index 93% index 7b45dce315..0d036279a9 100644 --- a/Doc/texinputs/copyright.tex +++ b/Doc/texinputs/copyright.tex @@ -1,108 +1,14 @@ -\begin{small} -Copyright \copyright{} 2001 Python Software Foundation. -All rights reserved. - -Copyright \copyright{} 2000 BeOpen.com. -All rights reserved. - -Copyright \copyright{} 1995-2000 Corporation for National Research Initiatives. -All rights reserved. - -Copyright \copyright{} 1991-1995 Stichting Mathematisch Centrum. -All rights reserved. - -%%begin{latexonly} -\vskip 4mm -%%end{latexonly} - -\centerline{\strong{BEOPEN.COM TERMS AND CONDITIONS FOR PYTHON 2.0}} - -\centerline{\strong{BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1}} - -\begin{enumerate} - -\item -This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an -office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the -Individual or Organization (``Licensee'') accessing and otherwise -using this software in source or binary form and its associated -documentation (``the Software''). - -\item -Subject to the terms and conditions of this BeOpen Python License -Agreement, BeOpen hereby grants Licensee a non-exclusive, -royalty-free, world-wide license to reproduce, analyze, test, perform -and/or display publicly, prepare derivative works, distribute, and -otherwise use the Software alone or in any derivative version, -provided, however, that the BeOpen Python License is retained in the -Software, alone or in any derivative version prepared by Licensee. - -\item -BeOpen is making the Software available to Licensee on an ``AS IS'' -basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR -IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND -DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS -FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT -INFRINGE ANY THIRD PARTY RIGHTS. - -\item -BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE -SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS -AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY -DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. - -\item -This License Agreement will automatically terminate upon a material -breach of its terms and conditions. - -\item -This License Agreement shall be governed by and interpreted in all -respects by the law of the State of California, excluding conflict of -law provisions. Nothing in this License Agreement shall be deemed to -create any relationship of agency, partnership, or joint venture -between BeOpen and Licensee. This License Agreement does not grant -permission to use BeOpen trademarks or trade names in a trademark -sense to endorse or promote products or services of Licensee, or any -third party. As an exception, the ``BeOpen Python'' logos available -at http://www.pythonlabs.com/logos.html may be used according to the -permissions granted on that web page. - -\item -By copying, installing or otherwise using the software, Licensee -agrees to be bound by the terms and conditions of this License -Agreement. -\end{enumerate} - - -\centerline{\strong{CNRI OPEN SOURCE GPL-COMPATIBLE LICENSE AGREEMENT}} - -Python 1.6.1 is made available subject to the terms and conditions in -CNRI's License Agreement. This Agreement together with Python 1.6.1 may -be located on the Internet using the following unique, persistent -identifier (known as a handle): 1895.22/1013. This Agreement may also -be obtained from a proxy server on the Internet using the following -URL: \url{http://hdl.handle.net/1895.22/1013}. - - -\centerline{\strong{CWI PERMISSIONS STATEMENT AND DISCLAIMER}} - -Copyright \copyright{} 1991 - 1995, Stichting Mathematisch Centrum -Amsterdam, The Netherlands. All rights reserved. - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, -provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in -supporting documentation, and that the name of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior -permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE -FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -\end{small} +Copyright \copyright{} 2001-2002 Python Software Foundation. +All rights reserved. + +Copyright \copyright{} 2000 BeOpen.com. +All rights reserved. + +Copyright \copyright{} 1995-2000 Corporation for National Research Initiatives. +All rights reserved. + +Copyright \copyright{} 1991-1995 Stichting Mathematisch Centrum. +All rights reserved. + +See the end of this document for complete license and permissions +information. diff --git a/LICENSE b/Doc/texinputs/license.tex similarity index 54% copy from LICENSE copy to Doc/texinputs/license.tex index 465f691042..472ce55103 100644 --- a/LICENSE +++ b/Doc/texinputs/license.tex @@ -1,5 +1,4 @@ -A. HISTORY OF THE SOFTWARE -========================== +\section{History of the software} Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI) in the Netherlands as a successor of a @@ -20,96 +19,97 @@ License (GPL) was very desirable. CNRI and the Free Software Foundation (FSF) interacted to develop enabling wording changes to the Python license. Python 1.6.1 is essentially the same as Python 1.6, with a few minor bug fixes, and with a different license that enables -later versions to be GPL-compatible. Python 2.1 is a derivative work +later versions to be GPL-compatible. Python 2.0.1 is a derivative work of Python 1.6.1, as well as of Python 2.0. After Python 2.0 was released by BeOpen.com, Guido van Rossum and the other PythonLabs developers joined Digital Creations. All -intellectual property added from this point on, starting with Python -2.1 and its alpha and beta releases, is owned by the Python Software -Foundation (PSF), a non-profit modeled after the Apache Software -Foundation. See http://www.python.org/psf/ for more information about -the PSF. +intellectual property added from this point on, including Python +2.0.1 and its alpha and beta releases, and Python 2.1.1, is owned by +the Python Software Foundation (PSF), a non-profit modeled after the +Apache Software Foundation. See \url{http://www.python.org/psf/} for +more information about the PSF. Thanks to the many outside volunteers who have worked under Guido's direction to make these releases possible. -B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON -=============================================================== +\section{Terms and conditions for accessing or otherwise using Python} -PSF LICENSE AGREEMENT ---------------------- +\centerline{\strong{PSF LICENSE AGREEMENT}} -1. This LICENSE AGREEMENT is between the Python Software Foundation -("PSF"), and the Individual or Organization ("Licensee") accessing and -otherwise using Python 2.1 software in source or binary form and its -associated documentation. +\begin{enumerate} +\item +This LICENSE AGREEMENT is between the Python Software Foundation +(``PSF''), and the Individual or Organization (``Licensee'') accessing +and otherwise using Python \version{} software in source or binary +form and its associated documentation. -2. Subject to the terms and conditions of this License Agreement, PSF +\item +Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, -prepare derivative works, distribute, and otherwise use Python 2.1 -alone or in any derivative version, provided, however, that PSF's -License Agreement and PSF's notice of copyright, i.e., "Copyright (c) -2001 Python Software Foundation; All Rights Reserved" are retained in -Python 2.1 alone or in any derivative version prepared by Licensee. - -3. In the event Licensee prepares a derivative work that is based on -or incorporates Python 2.1 or any part thereof, and wants to make -the derivative work available to others as provided herein, then +prepare derivative works, distribute, and otherwise use Python +\version{} alone or in any derivative version, provided, however, that +PSF's License Agreement and PSF's notice of copyright, i.e., +``Copyright \copyright{} 2001 Python Software Foundation; All Rights +Reserved'' are retained in Python \version{} alone or in any +derivative version prepared by Licensee. + +\item +In the event Licensee prepares a derivative work that is based on +or incorporates Python \version{} or any part thereof, and wants to +make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of -the changes made to Python 2.1. +the changes made to Python \version. -4. PSF is making Python 2.1 available to Licensee on an "AS IS" +\item +PSF is making Python \version{} available to Licensee on an ``AS IS'' basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS -FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.1 WILL NOT -INFRINGE ANY THIRD PARTY RIGHTS. - -5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON -2.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS -A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.1, -OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. - -6. This License Agreement will automatically terminate upon a material +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON \version{} WILL +NOT INFRINGE ANY THIRD PARTY RIGHTS. + +\item +PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +\version{} FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR +LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON +\version, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE +POSSIBILITY THEREOF. + +\item +This License Agreement will automatically terminate upon a material breach of its terms and conditions. -7. This License Agreement shall be governed by the federal -intellectual property law of the United States, including without -limitation the federal copyright law, and, to the extent such -U.S. federal law does not apply, by the law of the Commonwealth of -Virginia, excluding Virginia's conflict of law provisions. -Notwithstanding the foregoing, with regard to derivative works based -on Python 2.1 that incorporate non-separable material that was -previously distributed under the GNU General Public License (GPL), the -law of the Commonwealth of Virginia shall govern this License -Agreement only as to issues arising under or with respect to -Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this -License Agreement shall be deemed to create any relationship of -agency, partnership, or joint venture between PSF and Licensee. This -License Agreement does not grant permission to use PSF trademarks or -trade name in a trademark sense to endorse or promote products or -services of Licensee, or any third party. +\item +Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. -8. By copying, installing or otherwise using Python 2.1, Licensee +\item +By copying, installing or otherwise using Python \version, Licensee agrees to be bound by the terms and conditions of this License Agreement. +\end{enumerate} -BEOPEN.COM TERMS AND CONDITIONS FOR PYTHON 2.0 ----------------------------------------------- +\centerline{\strong{BEOPEN.COM TERMS AND CONDITIONS FOR PYTHON 2.0}} -BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 +\centerline{\strong{BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1}} -1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +\begin{enumerate} +\item +This LICENSE AGREEMENT is between BeOpen.com (``BeOpen''), having an office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the -Individual or Organization ("Licensee") accessing and otherwise using -this software in source or binary form and its associated -documentation ("the Software"). +Individual or Organization (``Licensee'') accessing and otherwise +using this software in source or binary form and its associated +documentation (``the Software''). -2. Subject to the terms and conditions of this BeOpen Python License +\item +Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and @@ -117,85 +117,99 @@ otherwise use the Software alone or in any derivative version, provided, however, that the BeOpen Python License is retained in the Software, alone or in any derivative version prepared by Licensee. -3. BeOpen is making the Software available to Licensee on an "AS IS" +\item +BeOpen is making the Software available to Licensee on an ``AS IS'' basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. -4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +\item +BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. -5. This License Agreement will automatically terminate upon a material +\item +This License Agreement will automatically terminate upon a material breach of its terms and conditions. -6. This License Agreement shall be governed by and interpreted in all +\item +This License Agreement shall be governed by and interpreted in all respects by the law of the State of California, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License Agreement does not grant permission to use BeOpen trademarks or trade names in a trademark sense to endorse or promote products or services of Licensee, or any -third party. As an exception, the "BeOpen Python" logos available at -http://www.pythonlabs.com/logos.html may be used according to the +third party. As an exception, the ``BeOpen Python'' logos available +at http://www.pythonlabs.com/logos.html may be used according to the permissions granted on that web page. -7. By copying, installing or otherwise using the software, Licensee +\item +By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and conditions of this License Agreement. +\end{enumerate} -CNRI OPEN SOURCE GPL-COMPATIBLE LICENSE AGREEMENT -------------------------------------------------- +\centerline{\strong{CNRI OPEN SOURCE GPL-COMPATIBLE LICENSE AGREEMENT}} -1. This LICENSE AGREEMENT is between the Corporation for National +\begin{enumerate} +\item +This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an office at 1895 Preston White Drive, -Reston, VA 20191 ("CNRI"), and the Individual or Organization -("Licensee") accessing and otherwise using Python 1.6.1 software in +Reston, VA 20191 (``CNRI''), and the Individual or Organization +(``Licensee'') accessing and otherwise using Python 1.6.1 software in source or binary form and its associated documentation. -2. Subject to the terms and conditions of this License Agreement, CNRI +\item +Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone or in any derivative version, provided, however, that CNRI's -License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) -1995-2001 Corporation for National Research Initiatives; All Rights -Reserved" are retained in Python 1.6.1 alone or in any derivative -version prepared by Licensee. Alternately, in lieu of CNRI's License -Agreement, Licensee may substitute the following text (omitting the -quotes): "Python 1.6.1 is made available subject to the terms and -conditions in CNRI's License Agreement. This Agreement together with -Python 1.6.1 may be located on the Internet using the following -unique, persistent identifier (known as a handle): 1895.22/1013. This -Agreement may also be obtained from a proxy server on the Internet -using the following URL: http://hdl.handle.net/1895.22/1013". - -3. In the event Licensee prepares a derivative work that is based on +License Agreement and CNRI's notice of copyright, i.e., ``Copyright +\copyright{} 1995-2001 Corporation for National Research Initiatives; +All Rights Reserved'' are retained in Python 1.6.1 alone or in any +derivative version prepared by Licensee. Alternately, in lieu of +CNRI's License Agreement, Licensee may substitute the following text +(omitting the quotes): ``Python 1.6.1 is made available subject to the +terms and conditions in CNRI's License Agreement. This Agreement +together with Python 1.6.1 may be located on the Internet using the +following unique, persistent identifier (known as a handle): +1895.22/1013. This Agreement may also be obtained from a proxy server +on the Internet using the following URL: +\url{http://hdl.handle.net/1895.22/1013}.'' + +\item +In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 1.6.1. -4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +\item +CNRI is making Python 1.6.1 available to Licensee on an ``AS IS'' basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. -5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +\item +CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. -6. This License Agreement will automatically terminate upon a material +\item +This License Agreement will automatically terminate upon a material breach of its terms and conditions. -7. This License Agreement shall be governed by the federal +\item +This License Agreement shall be governed by the federal intellectual property law of the United States, including without limitation the federal copyright law, and, to the extent such U.S. federal law does not apply, by the law of the Commonwealth of @@ -212,18 +226,20 @@ License Agreement does not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. -8. By clicking on the "ACCEPT" button where indicated, or by copying, +\item +By clicking on the ``ACCEPT'' button where indicated, or by copying, installing or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement. +\end{enumerate} + +\centerline{ACCEPT} - ACCEPT -CWI PERMISSIONS STATEMENT AND DISCLAIMER ----------------------------------------- +\centerline{\strong{CWI PERMISSIONS STATEMENT AND DISCLAIMER}} -Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, -The Netherlands. All rights reserved. +Copyright \copyright{} 1991 - 1995, Stichting Mathematisch Centrum +Amsterdam, The Netherlands. All rights reserved. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, diff --git a/Doc/texinputs/python.sty b/Doc/texinputs/python.sty index 8a61d87753..e4c60b834b 100644 --- a/Doc/texinputs/python.sty +++ b/Doc/texinputs/python.sty @@ -623,6 +623,15 @@ \index{#1@{\py@idxcode{#1}} (class in \py@thismodule)}] }{\end{fulllineitems}} +% \begin{classdesc*}{name} +\newenvironment{classdesc*}[1]{ + % Using \renewcommand doesn't work for this, for unknown reasons: + \global\def\py@thisclass{#1} + \begin{fulllineitems} + \item[\strong{class }\code{\bfcode{#1}}% + \index{#1@{\py@idxcode{#1}} (class in \py@thismodule)}] +}{\end{fulllineitems}} + % \begin{excclassdesc}{name}{constructor args} % but indexes as an exception \newenvironment{excclassdesc}[2]{ @@ -633,6 +642,9 @@ \index{#1@{\py@idxcode{#1}} (exception in \py@thismodule)}] }{\end{fulllineitems}} +% There is no corresponding {excclassdesc*} environment. To describe +% a class exception without parameters, use the {excdesc} environment. + \let\py@classbadkey=\@undefined @@ -872,8 +884,13 @@ % \versionadded{1.5.2} % \versionchanged[short explanation]{2.0} % -\newcommand{\versionadded}[1]{% - { New in version #1. }} +\newcommand{\versionadded}[2][\py@badkey]{% + \ifx#1\@undefined% + { New in version #2. }% + \else% + { New in version #2:\ #1. }% + \fi% +} \newcommand{\versionchanged}[2][\py@badkey]{% \ifx#1\@undefined% { Changed in version #2. }% @@ -1031,12 +1048,15 @@ \newcommand{\py@release}{} \newcommand{\version}{} \newcommand{\shortversion}{} +\newcommand{\releaseinfo}{} \newcommand{\releasename}{Release} \newcommand{\release}[1]{% \renewcommand{\py@release}{\releasename\space\version}% \renewcommand{\version}{#1}} \newcommand{\setshortversion}[1]{% \renewcommand{\shortversion}{#1}} +\newcommand{\setreleaseinfo}[1]{% + \renewcommand{\releaseinfo}{#1}} % Allow specification of the author's address separately from the % author's name. This can be used to format them differently, which diff --git a/Doc/tools/mkhowto b/Doc/tools/mkhowto index f11eec1dbd..6481e93e2b 100755 --- a/Doc/tools/mkhowto +++ b/Doc/tools/mkhowto @@ -369,24 +369,23 @@ class Job: shutil.copyfile(os.path.join(builddir, self.doc + ".html"), os.path.join(builddir, "index.html")) if max_split_depth != 1: - if self.options.numeric: - label_file = os.path.join(builddir, "labels.pl") - fp = open(label_file) - about_node = None - target = " = q/about/;\n" - x = len(target) - while 1: + label_file = os.path.join(builddir, "labels.pl") + fp = open(label_file) + about_node = None + target = " = q/about/;\n" + x = len(target) + while 1: + line = fp.readline() + if not line: + break + if line[-x:] == target: line = fp.readline() - if not line: - break - if line[-x:] == target: - line = fp.readline() - m = re.search(r"\|(node\d+\.[a-z]+)\|", line) - about_node = m.group(1) - shutil.copyfile(os.path.join(builddir, about_node), - os.path.join(builddir, "about.html")) - break - else: + m = re.search(r"\|(node\d+\.[a-z]+)\|", line) + about_node = m.group(1) + shutil.copyfile(os.path.join(builddir, about_node), + os.path.join(builddir, "about.html")) + break + if not self.options.numeric: pwd = os.getcwd() try: os.chdir(builddir) diff --git a/Doc/tools/mkmodindex b/Doc/tools/mkmodindex index 5f2da0ebc1..23a200e7eb 100755 --- a/Doc/tools/mkmodindex +++ b/Doc/tools/mkmodindex @@ -49,26 +49,30 @@ class IndexOptions(support.Options): class Node(buildindex.Node): - annotation = "" - - def __init__(self, link, str, seqno): - parts = string.split(str, None, 1) - if parts[0][-5:] == "": - self.modname = parts[0][:-5] - else: - self.modname = parts[0] - if len(parts) == 2: - self.annotation = parts[1] + def __init__(self, link, str, seqno, platinfo): + self.annotation = platinfo or None + if str[0][-5:] == "": + str = str[:-5] + self.modname = str buildindex.Node.__init__(self, link, self.modname, seqno) + if platinfo: + s = '%s %s' \ + % (self.modname, self.annotation) + else: + s = '%s' % str + self.text = [s] def __str__(self): - return '%s %s' \ - % (self.modname, self.annotation) + if self.annotation: + return '%s %s' \ + % (self.modname, self.annotation) + else: + return '%s' % self.modname _rx = re.compile( - "
" - "([a-zA-Z_][a-zA-Z0-9_.]*(\s*" - "\(.*\))?)") + "
" + "([a-zA-Z_][a-zA-Z0-9_.]*)\s*(" + "\(.*\))?") def main(): options = IndexOptions() @@ -81,7 +85,6 @@ def main(): # Collect the input data: # nodes = [] - seqno = 0 has_plat_flag = 0 for ifn in args: if ifn == "-": @@ -97,11 +100,11 @@ def main(): m = _rx.match(line) if m: # This line specifies a module! - basename, modname = m.group(1, 2) - has_plat_flag = has_plat_flag or m.group(3) + basename, modname, platinfo = m.group(1, 2, 3) + has_plat_flag = has_plat_flag or platinfo linkfile = os.path.join(dirname, basename) - nodes.append(Node('' % linkfile, modname, seqno)) - seqno = seqno + 1 + nodes.append(Node('' % linkfile, modname, + len(nodes), platinfo)) ifp.close() # # Generate all output: diff --git a/Doc/tools/push-docs.sh b/Doc/tools/push-docs.sh index c227bcf4cc..11a5f336ea 100755 --- a/Doc/tools/push-docs.sh +++ b/Doc/tools/push-docs.sh @@ -3,18 +3,57 @@ # Script to push docs from my development area to SourceForge, where the # update-docs.sh script unpacks them into their final destination. -TARGET=python.sourceforge.net:/home/users/fdrake/tmp +TARGET=python.sourceforge.net:/home/users/f/fd/fdrake/tmp ADDRESSES='python-dev@python.org doc-sig@python.org python-list@python.org' +VERSION=`echo '$Revision$' | sed 's/[$]Revision: \(.*\) [$]/\1/'` +EXTRA=`echo "$VERSION" | sed 's/^[0-9][0-9]*\.[0-9][0-9]*//'` +if [ "$EXTRA" ] ; then + DOCLABEL="maintenance" + DOCTYPE="maint" +else + DOCLABEL="development" + DOCTYPE="devel" +fi + EXPLANATION='' +ANNOUNCE=true -if [ "$1" = '-m' ] ; then - EXPLANATION="$2" - shift 2 -elif [ "$1" ] ; then - EXPLANATION="`cat $1`" - shift 1 +while [ "$#" -gt 0 ] ; do + case "$1" in + -m) + EXPLANATION="$2" + shift 2 + ;; + -q) + ANNOUNCE=false + shift 1 + ;; + -t) + DOCTYPE="$2" + shift 2 + ;; + -F) + EXPLANATION="`cat $2`" + shift 2 + ;; + -*) + echo "Unknown option: $1" >&2 + exit 2 + ;; + *) + break + ;; + esac +done +if [ "$1" ] ; then + if [ "$EXPLANATION" ] ; then + echo "Explanation may only be given once!" >&2 + exit 2 + fi + EXPLANATION="$1" + shift fi START="`pwd`" @@ -25,18 +64,23 @@ MYDIR="`pwd`" cd .. # now in .../Doc/ -make --no-print-directory || exit $? make --no-print-directory bziphtml || exit $? RELEASE=`grep '^RELEASE=' Makefile | sed 's|RELEASE=||'` PACKAGE="html-$RELEASE.tar.bz2" scp "$PACKAGE" tools/update-docs.sh $TARGET/ || exit $? -ssh python.sourceforge.net tmp/update-docs.sh $PACKAGE '&&' rm tmp/update-docs.sh || exit $? +ssh python.sourceforge.net tmp/update-docs.sh $DOCTYPE $PACKAGE '&&' rm tmp/update-docs.sh || exit $? -Mail -s '[development doc updates]' $ADDRESSES < +Subject: [$DOCLABEL doc updates] - http://python.sourceforge.net/devel-docs/ +The $DOCLABEL version of the documentation has been updated: + + http://python.sourceforge.net/$DOCTYPE-docs/ $EXPLANATION EOF -exit $? + exit $? +fi diff --git a/Doc/tools/update-docs.sh b/Doc/tools/update-docs.sh index 79652aca4e..5f4b03d79e 100755 --- a/Doc/tools/update-docs.sh +++ b/Doc/tools/update-docs.sh @@ -11,11 +11,20 @@ if [ -z "$HOME" ] ; then export HOME fi -UPDATES="$HOME/tmp/$1" +DOCTYPE="$1" +UPDATES="$HOME/tmp/$2" -cd /home/groups/python/htdocs || exit $? -rm -rf devel-docs || exit $? -mkdir devel-docs || exit $? -cd devel-docs || exit $? +TMPDIR="$$-docs" + +cd /home/groups/p/py/python/htdocs || exit $? +mkdir $TMPDIR || exit $? +cd $TMPDIR || exit $? (bzip2 -dc "$UPDATES" | tar xf -) || exit $? +cd .. || exit $? + +if [ -d $DOCTYPE-docs ] ; then + mv $DOCTYPE-docs $DOCTYPE-temp +fi +mv $TMPDIR $DOCTYPE-docs +rm -rf $DOCTYPE-temp || exit $? rm "$UPDATES" || exit $? diff --git a/Doc/tut/tut.tex b/Doc/tut/tut.tex index 69ff7ed81a..fb9ee543bc 100644 --- a/Doc/tut/tut.tex +++ b/Doc/tut/tut.tex @@ -427,7 +427,7 @@ operands convert the integer operand to floating point: \begin{verbatim} >>> 4 * 2.5 / 3.3 -3.0303030303 +3.0303030303030303 >>> 7.0 / 2 3.5 \end{verbatim} @@ -477,7 +477,7 @@ TypeError: can't convert complex to float; use e.g. abs(z) >>> a.real 1.5 >>> abs(a) -1.58113883008 +1.5811388300841898 \end{verbatim} In interactive mode, the last printed expression is assigned to the @@ -2609,10 +2609,10 @@ reverse quotes (\code{``}). Some examples: \begin{verbatim} >>> x = 10 * 3.14 ->>> y = 200*200 +>>> y = 200 * 200 >>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...' >>> print s -The value of x is 31.4, and y is 40000... +The value of x is 31.400000000000002, and y is 40000... >>> # Reverse quotes work on other types besides numbers: ... p = [x, y] >>> ps = repr(p) @@ -3424,7 +3424,7 @@ this: class MyClass: "A simple example class" i = 12345 - def f(x): + def f(self): return 'hello world' \end{verbatim} @@ -4059,15 +4059,52 @@ import rlcompleter, readline readline.parse_and_bind('tab: complete') \end{verbatim} -This binds the TAB key to the completion function, so hitting the TAB -key twice suggests completions; it looks at Python statement names, -the current local variables, and the available module names. For -dotted expressions such as \code{string.a}, it will evaluate the the -expression up to the final \character{.} and then suggest completions -from the attributes of the resulting object. Note that this may -execute application-defined code if an object with a +This binds the \kbd{Tab} key to the completion function, so hitting +the \kbd{Tab} key twice suggests completions; it looks at Python +statement names, the current local variables, and the available module +names. For dotted expressions such as \code{string.a}, it will +evaluate the the expression up to the final \character{.} and then +suggest completions from the attributes of the resulting object. Note +that this may execute application-defined code if an object with a \method{__getattr__()} method is part of the expression. +A more capable startup file might look like this example. Note that +this deletes the names it creates once they are no longer needed; this +is done since the startup file is executed in the same namespace as +the interactive commands, and removing the names avoids creating side +effects in the interactive environments. You may find it convenient +to keep some of the imported modules, such as \module{os}, which turn +out to be needed in most sessions with the interpreter. + +\begin{verbatim} +# Add auto-completion and a stored history file of commands to your Python +# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is +# bound to the Esc key by default (you can change it - see readline docs). +# +# Store the file in ~/.pystartup, and set an environment variable to point +# to it, e.g. "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash. +# +# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the +# full path to your home directory. + +import atexit +import os +import readline +import rlcompleter + +historyPath = os.path.expanduser("~/.pyhistory") + +def save_history(historyPath=historyPath): + import readline + readline.write_history_file(historyPath) + +if os.path.exists(historyPath): + readline.read_history_file(historyPath) + +atexit.register(save_history) +del os, atexit, readline, rlcompleter, save_history, historyPath +\end{verbatim} + \section{Commentary \label{commentary}} @@ -4080,4 +4117,7 @@ check (or even suggest) matching parentheses, quotes, etc., would also be useful. +\chapter{History and License} +\input{license} + \end{document} diff --git a/Doc/whatsnew/whatsnew20.tex b/Doc/whatsnew/whatsnew20.tex deleted file mode 100644 index 4817dcfcf8..0000000000 --- a/Doc/whatsnew/whatsnew20.tex +++ /dev/null @@ -1,1335 +0,0 @@ -\documentclass{howto} - -% $Id$ - -\title{What's New in Python 2.0} -\release{1.01} -\author{A.M. Kuchling and Moshe Zadka} -\authoraddress{\email{amk1@bigfoot.com}, \email{moshez@math.huji.ac.il} } -\begin{document} -\maketitle\tableofcontents - -\section{Introduction} - -A new release of Python, version 2.0, will be released some time this -autumn. Beta versions are already available from -\url{http://www.pythonlabs.com/products/python2.0/}. This article -covers the exciting new features in 2.0, highlights some other useful -changes, and points out a few incompatible changes that may require -rewriting code. - -Python's development never completely stops between releases, and a -steady flow of bug fixes and improvements are always being submitted. -A host of minor fixes, a few optimizations, additional docstrings, and -better error messages went into 2.0; to list them all would be -impossible, but they're certainly significant. Consult the -publicly-available CVS logs if you want to see the full list. This -progress is due to the five developers working for -PythonLabs are now getting paid to spend their days fixing bugs, -and also due to the improved communication resulting -from moving to SourceForge. - -% ====================================================================== -\section{What About Python 1.6?} - -Python 1.6 can be thought of as the Contractual Obligations Python -release. After the core development team left CNRI in May 2000, CNRI -requested that a 1.6 release be created, containing all the work on -Python that had been performed at CNRI. Python 1.6 therefore -represents the state of the CVS tree as of May 2000, with the most -significant new feature being Unicode support. Development continued -after May, of course, so the 1.6 tree received a few fixes to ensure -that it's forward-compatible with Python 2.0. 1.6 is therefore part -of Python's evolution, and not a side branch. - -So, should you take much interest in Python 1.6? Probably not. The -1.6final and 2.0beta1 releases were made on the same day (September 5, -2000), the plan being to finalize Python 2.0 within a month or so. If -you have applications to maintain, there seems little point in -breaking things by moving to 1.6, fixing them, and then having another -round of breakage within a month by moving to 2.0; you're better off -just going straight to 2.0. Most of the really interesting features -described in this document are only in 2.0, because a lot of work was -done between May and September. - -% ====================================================================== -\section{New Development Process} - -The most important change in Python 2.0 may not be to the code at all, -but to how Python is developed: in May 2000 the Python developers -began using the tools made available by SourceForge for storing -source code, tracking bug reports, and managing the queue of patch -submissions. To report bugs or submit patches for Python 2.0, use the -bug tracking and patch manager tools available from Python's project -page, located at \url{http://sourceforge.net/projects/python/}. - -The most important of the services now hosted at SourceForge is the -Python CVS tree, the version-controlled repository containing the -source code for Python. Previously, there were roughly 7 or so people -who had write access to the CVS tree, and all patches had to be -inspected and checked in by one of the people on this short list. -Obviously, this wasn't very scalable. By moving the CVS tree to -SourceForge, it became possible to grant write access to more people; -as of September 2000 there were 27 people able to check in changes, a -fourfold increase. This makes possible large-scale changes that -wouldn't be attempted if they'd have to be filtered through the small -group of core developers. For example, one day Peter Schneider-Kamp -took it into his head to drop K\&R C compatibility and convert the C -source for Python to ANSI C. After getting approval on the python-dev -mailing list, he launched into a flurry of checkins that lasted about -a week, other developers joined in to help, and the job was done. If -there were only 5 people with write access, probably that task would -have been viewed as ``nice, but not worth the time and effort needed'' -and it would never have gotten done. - -The shift to using SourceForge's services has resulted in a remarkable -increase in the speed of development. Patches now get submitted, -commented on, revised by people other than the original submitter, and -bounced back and forth between people until the patch is deemed worth -checking in. Bugs are tracked in one central location and can be -assigned to a specific person for fixing, and we can count the number -of open bugs to measure progress. This didn't come without a cost: -developers now have more e-mail to deal with, more mailing lists to -follow, and special tools had to be written for the new environment. -For example, SourceForge sends default patch and bug notification -e-mail messages that are completely unhelpful, so Ka-Ping Yee wrote an -HTML screen-scraper that sends more useful messages. - -The ease of adding code caused a few initial growing pains, such as -code was checked in before it was ready or without getting clear -agreement from the developer group. The approval process that has -emerged is somewhat similar to that used by the Apache group. -Developers can vote +1, +0, -0, or -1 on a patch; +1 and -1 denote -acceptance or rejection, while +0 and -0 mean the developer is mostly -indifferent to the change, though with a slight positive or negative -slant. The most significant change from the Apache model is that the -voting is essentially advisory, letting Guido van Rossum, who has -Benevolent Dictator For Life status, know what the general opinion is. -He can still ignore the result of a vote, and approve or -reject a change even if the community disagrees with him. - -Producing an actual patch is the last step in adding a new feature, -and is usually easy compared to the earlier task of coming up with a -good design. Discussions of new features can often explode into -lengthy mailing list threads, making the discussion hard to follow, -and no one can read every posting to python-dev. Therefore, a -relatively formal process has been set up to write Python Enhancement -Proposals (PEPs), modelled on the Internet RFC process. PEPs are -draft documents that describe a proposed new feature, and are -continually revised until the community reaches a consensus, either -accepting or rejecting the proposal. Quoting from the introduction to -PEP 1, ``PEP Purpose and Guidelines'': - -\begin{quotation} - PEP stands for Python Enhancement Proposal. A PEP is a design - document providing information to the Python community, or - describing a new feature for Python. The PEP should provide a - concise technical specification of the feature and a rationale for - the feature. - - We intend PEPs to be the primary mechanisms for proposing new - features, for collecting community input on an issue, and for - documenting the design decisions that have gone into Python. The - PEP author is responsible for building consensus within the - community and documenting dissenting opinions. -\end{quotation} - -Read the rest of PEP 1 for the details of the PEP editorial process, -style, and format. PEPs are kept in the Python CVS tree on -SourceForge, though they're not part of the Python 2.0 distribution, -and are also available in HTML form from -\url{http://python.sourceforge.net/peps/}. As of September 2000, -there are 25 PEPS, ranging from PEP 201, ``Lockstep Iteration'', to -PEP 225, ``Elementwise/Objectwise Operators''. - -% ====================================================================== -\section{Unicode} - -The largest new feature in Python 2.0 is a new fundamental data type: -Unicode strings. Unicode uses 16-bit numbers to represent characters -instead of the 8-bit number used by ASCII, meaning that 65,536 -distinct characters can be supported. - -The final interface for Unicode support was arrived at through -countless often-stormy discussions on the python-dev mailing list, and -mostly implemented by Marc-Andr\'e Lemburg, based on a Unicode string -type implementation by Fredrik Lundh. A detailed explanation of the -interface is in the file \file{Misc/unicode.txt} in the Python source -distribution; it's also available on the Web at -\url{http://starship.python.net/crew/lemburg/unicode-proposal.txt}. -This article will simply cover the most significant points about the Unicode -interfaces. - -In Python source code, Unicode strings are written as -\code{u"string"}. Arbitrary Unicode characters can be written using a -new escape sequence, \code{\e u\var{HHHH}}, where \var{HHHH} is a -4-digit hexadecimal number from 0000 to FFFF. The existing -\code{\e x\var{HHHH}} escape sequence can also be used, and octal -escapes can be used for characters up to U+01FF, which is represented -by \code{\e 777}. - -Unicode strings, just like regular strings, are an immutable sequence -type. They can be indexed and sliced, but not modified in place. -Unicode strings have an \method{encode( \optional{encoding} )} method -that returns an 8-bit string in the desired encoding. Encodings are -named by strings, such as \code{'ascii'}, \code{'utf-8'}, -\code{'iso-8859-1'}, or whatever. A codec API is defined for -implementing and registering new encodings that are then available -throughout a Python program. If an encoding isn't specified, the -default encoding is usually 7-bit ASCII, though it can be changed for -your Python installation by calling the -\function{sys.setdefaultencoding(\var{encoding})} function in a -customised version of \file{site.py}. - -Combining 8-bit and Unicode strings always coerces to Unicode, using -the default ASCII encoding; the result of \code{'a' + u'bc'} is -\code{u'abc'}. - -New built-in functions have been added, and existing built-ins -modified to support Unicode: - -\begin{itemize} -\item \code{unichr(\var{ch})} returns a Unicode string 1 character -long, containing the character \var{ch}. - -\item \code{ord(\var{u})}, where \var{u} is a 1-character regular or Unicode string, returns the number of the character as an integer. - -\item \code{unicode(\var{string} \optional{, \var{encoding}} -\optional{, \var{errors}} ) } creates a Unicode string from an 8-bit -string. \code{encoding} is a string naming the encoding to use. -The \code{errors} parameter specifies the treatment of characters that -are invalid for the current encoding; passing \code{'strict'} as the -value causes an exception to be raised on any encoding error, while -\code{'ignore'} causes errors to be silently ignored and -\code{'replace'} uses U+FFFD, the official replacement character, in -case of any problems. - -\item The \keyword{exec} statement, and various built-ins such as -\code{eval()}, \code{getattr()}, and \code{setattr()} will also -accept Unicode strings as well as regular strings. (It's possible -that the process of fixing this missed some built-ins; if you find a -built-in function that accepts strings but doesn't accept Unicode -strings at all, please report it as a bug.) - -\end{itemize} - -A new module, \module{unicodedata}, provides an interface to Unicode -character properties. For example, \code{unicodedata.category(u'A')} -returns the 2-character string 'Lu', the 'L' denoting it's a letter, -and 'u' meaning that it's uppercase. -\code{u.bidirectional(u'\e x0660')} returns 'AN', meaning that U+0660 is -an Arabic number. - -The \module{codecs} module contains functions to look up existing encodings -and register new ones. Unless you want to implement a -new encoding, you'll most often use the -\function{codecs.lookup(\var{encoding})} function, which returns a -4-element tuple: \code{(\var{encode_func}, -\var{decode_func}, \var{stream_reader}, \var{stream_writer})}. - -\begin{itemize} -\item \var{encode_func} is a function that takes a Unicode string, and -returns a 2-tuple \code{(\var{string}, \var{length})}. \var{string} -is an 8-bit string containing a portion (perhaps all) of the Unicode -string converted into the given encoding, and \var{length} tells you -how much of the Unicode string was converted. - -\item \var{decode_func} is the opposite of \var{encode_func}, taking -an 8-bit string and returning a 2-tuple \code{(\var{ustring}, -\var{length})}, consisting of the resulting Unicode string -\var{ustring} and the integer \var{length} telling how much of the -8-bit string was consumed. - -\item \var{stream_reader} is a class that supports decoding input from -a stream. \var{stream_reader(\var{file_obj})} returns an object that -supports the \method{read()}, \method{readline()}, and -\method{readlines()} methods. These methods will all translate from -the given encoding and return Unicode strings. - -\item \var{stream_writer}, similarly, is a class that supports -encoding output to a stream. \var{stream_writer(\var{file_obj})} -returns an object that supports the \method{write()} and -\method{writelines()} methods. These methods expect Unicode strings, -translating them to the given encoding on output. -\end{itemize} - -For example, the following code writes a Unicode string into a file, -encoding it as UTF-8: - -\begin{verbatim} -import codecs - -unistr = u'\u0660\u2000ab ...' - -(UTF8_encode, UTF8_decode, - UTF8_streamreader, UTF8_streamwriter) = codecs.lookup('UTF-8') - -output = UTF8_streamwriter( open( '/tmp/output', 'wb') ) -output.write( unistr ) -output.close() -\end{verbatim} - -The following code would then read UTF-8 input from the file: - -\begin{verbatim} -input = UTF8_streamreader( open( '/tmp/output', 'rb') ) -print repr(input.read()) -input.close() -\end{verbatim} - -Unicode-aware regular expressions are available through the -\module{re} module, which has a new underlying implementation called -SRE written by Fredrik Lundh of Secret Labs AB. - -A \code{-U} command line option was added which causes the Python -compiler to interpret all string literals as Unicode string literals. -This is intended to be used in testing and future-proofing your Python -code, since some future version of Python may drop support for 8-bit -strings and provide only Unicode strings. - -% ====================================================================== -\section{List Comprehensions} - -Lists are a workhorse data type in Python, and many programs -manipulate a list at some point. Two common operations on lists are -to loop over them, and either pick out the elements that meet a -certain criterion, or apply some function to each element. For -example, given a list of strings, you might want to pull out all the -strings containing a given substring, or strip off trailing whitespace -from each line. - -The existing \function{map()} and \function{filter()} functions can be -used for this purpose, but they require a function as one of their -arguments. This is fine if there's an existing built-in function that -can be passed directly, but if there isn't, you have to create a -little function to do the required work, and Python's scoping rules -make the result ugly if the little function needs additional -information. Take the first example in the previous paragraph, -finding all the strings in the list containing a given substring. You -could write the following to do it: - -\begin{verbatim} -# Given the list L, make a list of all strings -# containing the substring S. -sublist = filter( lambda s, substring=S: - string.find(s, substring) != -1, - L) -\end{verbatim} - -Because of Python's scoping rules, a default argument is used so that -the anonymous function created by the \keyword{lambda} statement knows -what substring is being searched for. List comprehensions make this -cleaner: - -\begin{verbatim} -sublist = [ s for s in L if string.find(s, S) != -1 ] -\end{verbatim} - -List comprehensions have the form: - -\begin{verbatim} -[ expression for expr in sequence1 - for expr2 in sequence2 ... - for exprN in sequenceN - if condition -\end{verbatim} - -The \keyword{for}...\keyword{in} clauses contain the sequences to be -iterated over. The sequences do not have to be the same length, -because they are \emph{not} iterated over in parallel, but -from left to right; this is explained more clearly in the following -paragraphs. The elements of the generated list will be the successive -values of \var{expression}. The final \keyword{if} clause is -optional; if present, \var{expression} is only evaluated and added to -the result if \var{condition} is true. - -To make the semantics very clear, a list comprehension is equivalent -to the following Python code: - -\begin{verbatim} -for expr1 in sequence1: - for expr2 in sequence2: - ... - for exprN in sequenceN: - if (condition): - # Append the value of - # the expression to the - # resulting list. -\end{verbatim} - -This means that when there are \keyword{for}...\keyword{in} clauses, -the resulting list will be equal to the product of the lengths of all -the sequences. If you have two lists of length 3, the output list is -9 elements long: - -\begin{verbatim} -seq1 = 'abc' -seq2 = (1,2,3) ->>> [ (x,y) for x in seq1 for y in seq2] -[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), -('c', 2), ('c', 3)] -\end{verbatim} - -To avoid introducing an ambiguity into Python's grammar, if -\var{expression} is creating a tuple, it must be surrounded with -parentheses. The first list comprehension below is a syntax error, -while the second one is correct: - -\begin{verbatim} -# Syntax error -[ x,y for x in seq1 for y in seq2] -# Correct -[ (x,y) for x in seq1 for y in seq2] -\end{verbatim} - -The idea of list comprehensions originally comes from the functional -programming language Haskell (\url{http://www.haskell.org}). Greg -Ewing argued most effectively for adding them to Python and wrote the -initial list comprehension patch, which was then discussed for a -seemingly endless time on the python-dev mailing list and kept -up-to-date by Skip Montanaro. - -% ====================================================================== -\section{Augmented Assignment} - -Augmented assignment operators, another long-requested feature, have -been added to Python 2.0. Augmented assignment operators include -\code{+=}, \code{-=}, \code{*=}, and so forth. For example, the -statement \code{a += 2} increments the value of the variable -\code{a} by 2, equivalent to the slightly lengthier \code{a = a + 2}. - -The full list of supported assignment operators is \code{+=}, -\code{-=}, \code{*=}, \code{/=}, \code{\%=}, \code{**=}, \code{\&=}, -\code{|=}, \verb|^=|, \code{>>=}, and \code{<<=}. Python classes can -override the augmented assignment operators by defining methods named -\method{__iadd__}, \method{__isub__}, etc. For example, the following -\class{Number} class stores a number and supports using += to create a -new instance with an incremented value. - -\begin{verbatim} -class Number: - def __init__(self, value): - self.value = value - def __iadd__(self, increment): - return Number( self.value + increment) - -n = Number(5) -n += 3 -print n.value -\end{verbatim} - -The \method{__iadd__} special method is called with the value of the -increment, and should return a new instance with an appropriately -modified value; this return value is bound as the new value of the -variable on the left-hand side. - -Augmented assignment operators were first introduced in the C -programming language, and most C-derived languages, such as -\program{awk}, C++, Java, Perl, and PHP also support them. The augmented -assignment patch was implemented by Thomas Wouters. - -% ====================================================================== -\section{String Methods} - -Until now string-manipulation functionality was in the \module{string} -module, which was usually a front-end for the \module{strop} -module written in C. The addition of Unicode posed a difficulty for -the \module{strop} module, because the functions would all need to be -rewritten in order to accept either 8-bit or Unicode strings. For -functions such as \function{string.replace()}, which takes 3 string -arguments, that means eight possible permutations, and correspondingly -complicated code. - -Instead, Python 2.0 pushes the problem onto the string type, making -string manipulation functionality available through methods on both -8-bit strings and Unicode strings. - -\begin{verbatim} ->>> 'andrew'.capitalize() -'Andrew' ->>> 'hostname'.replace('os', 'linux') -'hlinuxtname' ->>> 'moshe'.find('sh') -2 -\end{verbatim} - -One thing that hasn't changed, a noteworthy April Fools' joke -notwithstanding, is that Python strings are immutable. Thus, the -string methods return new strings, and do not modify the string on -which they operate. - -The old \module{string} module is still around for backwards -compatibility, but it mostly acts as a front-end to the new string -methods. - -Two methods which have no parallel in pre-2.0 versions, although they -did exist in JPython for quite some time, are \method{startswith()} -and \method{endswith}. \code{s.startswith(t)} is equivalent to \code{s[:len(t)] -== t}, while \code{s.endswith(t)} is equivalent to \code{s[-len(t):] == t}. - -One other method which deserves special mention is \method{join}. The -\method{join} method of a string receives one parameter, a sequence of -strings, and is equivalent to the \function{string.join} function from -the old \module{string} module, with the arguments reversed. In other -words, \code{s.join(seq)} is equivalent to the old -\code{string.join(seq, s)}. - -% ====================================================================== -\section{Garbage Collection of Cycles} - -The C implementation of Python uses reference counting to implement -garbage collection. Every Python object maintains a count of the -number of references pointing to itself, and adjusts the count as -references are created or destroyed. Once the reference count reaches -zero, the object is no longer accessible, since you need to have a -reference to an object to access it, and if the count is zero, no -references exist any longer. - -Reference counting has some pleasant properties: it's easy to -understand and implement, and the resulting implementation is -portable, fairly fast, and reacts well with other libraries that -implement their own memory handling schemes. The major problem with -reference counting is that it sometimes doesn't realise that objects -are no longer accessible, resulting in a memory leak. This happens -when there are cycles of references. - -Consider the simplest possible cycle, -a class instance which has a reference to itself: - -\begin{verbatim} -instance = SomeClass() -instance.myself = instance -\end{verbatim} - -After the above two lines of code have been executed, the reference -count of \code{instance} is 2; one reference is from the variable -named \samp{'instance'}, and the other is from the \samp{myself} -attribute of the instance. - -If the next line of code is \code{del instance}, what happens? The -reference count of \code{instance} is decreased by 1, so it has a -reference count of 1; the reference in the \samp{myself} attribute -still exists. Yet the instance is no longer accessible through Python -code, and it could be deleted. Several objects can participate in a -cycle if they have references to each other, causing all of the -objects to be leaked. - -Python 2.0 fixes this problem by periodically executing a cycle -detection algorithm which looks for inaccessible cycles and deletes -the objects involved. A new \module{gc} module provides functions to -perform a garbage collection, obtain debugging statistics, and tuning -the collector's parameters. - -Running the cycle detection algorithm takes some time, and therefore -will result in some additional overhead. It is hoped that after we've -gotten experience with the cycle collection from using 2.0, Python 2.1 -will be able to minimize the overhead with careful tuning. It's not -yet obvious how much performance is lost, because benchmarking this is -tricky and depends crucially on how often the program creates and -destroys objects. The detection of cycles can be disabled when Python -is compiled, if you can't afford even a tiny speed penalty or suspect -that the cycle collection is buggy, by specifying the -\samp{--without-cycle-gc} switch when running the \file{configure} -script. - -Several people tackled this problem and contributed to a solution. An -early implementation of the cycle detection approach was written by -Toby Kelsey. The current algorithm was suggested by Eric Tiedemann -during a visit to CNRI, and Guido van Rossum and Neil Schemenauer -wrote two different implementations, which were later integrated by -Neil. Lots of other people offered suggestions along the way; the -March 2000 archives of the python-dev mailing list contain most of the -relevant discussion, especially in the threads titled ``Reference -cycle collection for Python'' and ``Finalization again''. - -% ====================================================================== -\section{Other Core Changes} - -Various minor changes have been made to Python's syntax and built-in -functions. None of the changes are very far-reaching, but they're -handy conveniences. - -\subsection{Minor Language Changes} - -A new syntax makes it more convenient to call a given function -with a tuple of arguments and/or a dictionary of keyword arguments. -In Python 1.5 and earlier, you'd use the \function{apply()} -built-in function: \code{apply(f, \var{args}, \var{kw})} calls the -function \function{f()} with the argument tuple \var{args} and the -keyword arguments in the dictionary \var{kw}. \function{apply()} -is the same in 2.0, but thanks to a patch from -Greg Ewing, \code{f(*\var{args}, **\var{kw})} as a shorter -and clearer way to achieve the same effect. This syntax is -symmetrical with the syntax for defining functions: - -\begin{verbatim} -def f(*args, **kw): - # args is a tuple of positional args, - # kw is a dictionary of keyword args - ... -\end{verbatim} - -The \keyword{print} statement can now have its output directed to a -file-like object by following the \keyword{print} with -\verb|>> file|, similar to the redirection operator in Unix shells. -Previously you'd either have to use the \method{write()} method of the -file-like object, which lacks the convenience and simplicity of -\keyword{print}, or you could assign a new value to -\code{sys.stdout} and then restore the old value. For sending output to standard error, -it's much easier to write this: - -\begin{verbatim} -print >> sys.stderr, "Warning: action field not supplied" -\end{verbatim} - -Modules can now be renamed on importing them, using the syntax -\code{import \var{module} as \var{name}} or \code{from \var{module} -import \var{name} as \var{othername}}. The patch was submitted by -Thomas Wouters. - -A new format style is available when using the \code{\%} operator; -'\%r' will insert the \function{repr()} of its argument. This was -also added from symmetry considerations, this time for symmetry with -the existing '\%s' format style, which inserts the \function{str()} of -its argument. For example, \code{'\%r \%s' \% ('abc', 'abc')} returns a -string containing \verb|'abc' abc|. - -Previously there was no way to implement a class that overrode -Python's built-in \keyword{in} operator and implemented a custom -version. \code{\var{obj} in \var{seq}} returns true if \var{obj} is -present in the sequence \var{seq}; Python computes this by simply -trying every index of the sequence until either \var{obj} is found or -an \exception{IndexError} is encountered. Moshe Zadka contributed a -patch which adds a \method{__contains__} magic method for providing a -custom implementation for \keyword{in}. Additionally, new built-in -objects written in C can define what \keyword{in} means for them via a -new slot in the sequence protocol. - -Earlier versions of Python used a recursive algorithm for deleting -objects. Deeply nested data structures could cause the interpreter to -fill up the C stack and crash; Christian Tismer rewrote the deletion -logic to fix this problem. On a related note, comparing recursive -objects recursed infinitely and crashed; Jeremy Hylton rewrote the -code to no longer crash, producing a useful result instead. For -example, after this code: - -\begin{verbatim} -a = [] -b = [] -a.append(a) -b.append(b) -\end{verbatim} - -The comparison \code{a==b} returns true, because the two recursive -data structures are isomorphic. See the thread ``trashcan -and PR\#7'' in the April 2000 archives of the python-dev mailing list -for the discussion leading up to this implementation, and some useful -relevant links. -% Starting URL: -% http://www.python.org/pipermail/python-dev/2000-April/004834.html - -Note that comparisons can now also raise exceptions. In earlier -versions of Python, a comparison operation such as \code{cmp(a,b)} -would always produce an answer, even if a user-defined -\method{__cmp__} method encountered an error, since the resulting -exception would simply be silently swallowed. - -Work has been done on porting Python to 64-bit Windows on the Itanium -processor, mostly by Trent Mick of ActiveState. (Confusingly, -\code{sys.platform} is still \code{'win32'} on Win64 because it seems -that for ease of porting, MS Visual C++ treats code as 32 bit on Itanium.) -PythonWin also supports Windows CE; see the Python CE page at -\url{http://starship.python.net/crew/mhammond/ce/} for more -information. - -Another new platform is Darwin/MacOS X; inital support for it is in -Python 2.0. Dynamic loading works, if you specify ``configure ---with-dyld --with-suffix=.x''. Consult the README in the Python -source distribution for more instructions. - -An attempt has been made to alleviate one of Python's warts, the -often-confusing \exception{NameError} exception when code refers to a -local variable before the variable has been assigned a value. For -example, the following code raises an exception on the \keyword{print} -statement in both 1.5.2 and 2.0; in 1.5.2 a \exception{NameError} -exception is raised, while 2.0 raises a new -\exception{UnboundLocalError} exception. -\exception{UnboundLocalError} is a subclass of \exception{NameError}, -so any existing code that expects \exception{NameError} to be raised -should still work. - -\begin{verbatim} -def f(): - print "i=",i - i = i + 1 -f() -\end{verbatim} - -Two new exceptions, \exception{TabError} and -\exception{IndentationError}, have been introduced. They're both -subclasses of \exception{SyntaxError}, and are raised when Python code -is found to be improperly indented. - -\subsection{Changes to Built-in Functions} - -A new built-in, \function{zip(\var{seq1}, \var{seq2}, ...)}, has been -added. \function{zip()} returns a list of tuples where each tuple -contains the i-th element from each of the argument sequences. The -difference between \function{zip()} and \code{map(None, \var{seq1}, -\var{seq2})} is that \function{map()} pads the sequences with -\code{None} if the sequences aren't all of the same length, while -\function{zip()} truncates the returned list to the length of the -shortest argument sequence. - -The \function{int()} and \function{long()} functions now accept an -optional ``base'' parameter when the first argument is a string. -\code{int('123', 10)} returns 123, while \code{int('123', 16)} returns -291. \code{int(123, 16)} raises a \exception{TypeError} exception -with the message ``can't convert non-string with explicit base''. - -A new variable holding more detailed version information has been -added to the \module{sys} module. \code{sys.version_info} is a tuple -\code{(\var{major}, \var{minor}, \var{micro}, \var{level}, -\var{serial})} For example, in a hypothetical 2.0.1beta1, -\code{sys.version_info} would be \code{(2, 0, 1, 'beta', 1)}. -\var{level} is a string such as \code{"alpha"}, \code{"beta"}, or -\code{"final"} for a final release. - -Dictionaries have an odd new method, \method{setdefault(\var{key}, -\var{default})}, which behaves similarly to the existing -\method{get()} method. However, if the key is missing, -\method{setdefault()} both returns the value of \var{default} as -\method{get()} would do, and also inserts it into the dictionary as -the value for \var{key}. Thus, the following lines of code: - -\begin{verbatim} -if dict.has_key( key ): return dict[key] -else: - dict[key] = [] - return dict[key] -\end{verbatim} - -can be reduced to a single \code{return dict.setdefault(key, [])} statement. - -The interpreter sets a maximum recursion depth in order to catch -runaway recursion before filling the C stack and causing a core dump -or GPF.. Previously this limit was fixed when you compiled Python, -but in 2.0 the maximum recursion depth can be read and modified using -\function{sys.getrecursionlimit} and \function{sys.setrecursionlimit}. -The default value is 1000, and a rough maximum value for a given -platform can be found by running a new script, -\file{Misc/find_recursionlimit.py}. - -% ====================================================================== -\section{Porting to 2.0} - -New Python releases try hard to be compatible with previous releases, -and the record has been pretty good. However, some changes are -considered useful enough, usually because they fix initial design decisions that -turned out to be actively mistaken, that breaking backward compatibility -can't always be avoided. This section lists the changes in Python 2.0 -that may cause old Python code to break. - -The change which will probably break the most code is tightening up -the arguments accepted by some methods. Some methods would take -multiple arguments and treat them as a tuple, particularly various -list methods such as \method{.append()} and \method{.insert()}. -In earlier versions of Python, if \code{L} is a list, \code{L.append( -1,2 )} appends the tuple \code{(1,2)} to the list. In Python 2.0 this -causes a \exception{TypeError} exception to be raised, with the -message: 'append requires exactly 1 argument; 2 given'. The fix is to -simply add an extra set of parentheses to pass both values as a tuple: -\code{L.append( (1,2) )}. - -The earlier versions of these methods were more forgiving because they -used an old function in Python's C interface to parse their arguments; -2.0 modernizes them to use \function{PyArg_ParseTuple}, the current -argument parsing function, which provides more helpful error messages -and treats multi-argument calls as errors. If you absolutely must use -2.0 but can't fix your code, you can edit \file{Objects/listobject.c} -and define the preprocessor symbol \code{NO_STRICT_LIST_APPEND} to -preserve the old behaviour; this isn't recommended. - -Some of the functions in the \module{socket} module are still -forgiving in this way. For example, \function{socket.connect( -('hostname', 25) )} is the correct form, passing a tuple representing -an IP address, but \function{socket.connect( 'hostname', 25 )} also -works. \function{socket.connect_ex()} and \function{socket.bind()} are -similarly easy-going. 2.0alpha1 tightened these functions up, but -because the documentation actually used the erroneous multiple -argument form, many people wrote code which would break with the -stricter checking. GvR backed out the changes in the face of public -reaction, so for the \module{socket} module, the documentation was -fixed and the multiple argument form is simply marked as deprecated; -it \emph{will} be tightened up again in a future Python version. - -The \code{\e x} escape in string literals now takes exactly 2 hex -digits. Previously it would consume all the hex digits following the -'x' and take the lowest 8 bits of the result, so \code{\e x123456} was -equivalent to \code{\e x56}. - -The \exception{AttributeError} exception has a more friendly error message, -whose text will be something like \code{'Spam' instance has no attribute 'eggs'}. -Previously the error message was just the missing attribute name \code{eggs}, and -code written to take advantage of this fact will break in 2.0. - -Some work has been done to make integers and long integers a bit more -interchangeable. In 1.5.2, large-file support was added for Solaris, -to allow reading files larger than 2Gb; this made the \method{tell()} -method of file objects return a long integer instead of a regular -integer. Some code would subtract two file offsets and attempt to use -the result to multiply a sequence or slice a string, but this raised a -\exception{TypeError}. In 2.0, long integers can be used to multiply -or slice a sequence, and it'll behave as you'd intuitively expect it -to; \code{3L * 'abc'} produces 'abcabcabc', and \code{ -(0,1,2,3)[2L:4L]} produces (2,3). Long integers can also be used in -various contexts where previously only integers were accepted, such -as in the \method{seek()} method of file objects, and in the formats -supported by the \verb|%| operator (\verb|%d|, \verb|%i|, \verb|%x|, -etc.). For example, \code{"\%d" \% 2L**64} will produce the string -\samp{18446744073709551616}. - -The subtlest long integer change of all is that the \function{str()} -of a long integer no longer has a trailing 'L' character, though -\function{repr()} still includes it. The 'L' annoyed many people who -wanted to print long integers that looked just like regular integers, -since they had to go out of their way to chop off the character. This -is no longer a problem in 2.0, but code which does \code{str(longval)[:-1]} and assumes the 'L' is there, will now lose -the final digit. - -Taking the \function{repr()} of a float now uses a different -formatting precision than \function{str()}. \function{repr()} uses -\code{\%.17g} format string for C's \function{sprintf()}, while -\function{str()} uses \code{\%.12g} as before. The effect is that -\function{repr()} may occasionally show more decimal places than -\function{str()}, for certain numbers. -For example, the number 8.1 can't be represented exactly in binary, so -\code{repr(8.1)} is \code{'8.0999999999999996'}, while str(8.1) is -\code{'8.1'}. - -The \code{-X} command-line option, which turned all standard -exceptions into strings instead of classes, has been removed; the -standard exceptions will now always be classes. The -\module{exceptions} module containing the standard exceptions was -translated from Python to a built-in C module, written by Barry Warsaw -and Fredrik Lundh. - -% Commented out for now -- I don't think anyone will care. -%The pattern and match objects provided by SRE are C types, not Python -%class instances as in 1.5. This means you can no longer inherit from -%\class{RegexObject} or \class{MatchObject}, but that shouldn't be much -%of a problem since no one should have been doing that in the first -%place. - -% ====================================================================== -\section{Extending/Embedding Changes} - -Some of the changes are under the covers, and will only be apparent to -people writing C extension modules or embedding a Python interpreter -in a larger application. If you aren't dealing with Python's C API, -you can safely skip this section. - -The version number of the Python C API was incremented, so C -extensions compiled for 1.5.2 must be recompiled in order to work with -2.0. On Windows, it's not possible for Python 2.0 to import a third -party extension built for Python 1.5.x due to how Windows DLLs work, -so Python will raise an exception and the import will fail. - -Users of Jim Fulton's ExtensionClass module will be pleased to find -out that hooks have been added so that ExtensionClasses are now -supported by \function{isinstance()} and \function{issubclass()}. -This means you no longer have to remember to write code such as -\code{if type(obj) == myExtensionClass}, but can use the more natural -\code{if isinstance(obj, myExtensionClass)}. - -The \file{Python/importdl.c} file, which was a mass of \#ifdefs to -support dynamic loading on many different platforms, was cleaned up -and reorganised by Greg Stein. \file{importdl.c} is now quite small, -and platform-specific code has been moved into a bunch of -\file{Python/dynload_*.c} files. Another cleanup: there were also a -number of \file{my*.h} files in the Include/ directory that held -various portability hacks; they've been merged into a single file, -\file{Include/pyport.h}. - -Vladimir Marangozov's long-awaited malloc restructuring was completed, -to make it easy to have the Python interpreter use a custom allocator -instead of C's standard \function{malloc()}. For documentation, read -the comments in \file{Include/pymem.h} and -\file{Include/objimpl.h}. For the lengthy discussions during which -the interface was hammered out, see the Web archives of the 'patches' -and 'python-dev' lists at python.org. - -Recent versions of the GUSI development environment for MacOS support -POSIX threads. Therefore, Python's POSIX threading support now works -on the Macintosh. Threading support using the user-space GNU \texttt{pth} -library was also contributed. - -Threading support on Windows was enhanced, too. Windows supports -thread locks that use kernel objects only in case of contention; in -the common case when there's no contention, they use simpler functions -which are an order of magnitude faster. A threaded version of Python -1.5.2 on NT is twice as slow as an unthreaded version; with the 2.0 -changes, the difference is only 10\%. These improvements were -contributed by Yakov Markovitch. - -Python 2.0's source now uses only ANSI C prototypes, so compiling Python now -requires an ANSI C compiler, and can no longer be done using a compiler that -only supports K\&R C. - -Previously the Python virtual machine used 16-bit numbers in its -bytecode, limiting the size of source files. In particular, this -affected the maximum size of literal lists and dictionaries in Python -source; occasionally people who are generating Python code would run -into this limit. A patch by Charles G. Waldman raises the limit from -\verb|2^16| to \verb|2^{32}|. - -Three new convenience functions intended for adding constants to a -module's dictionary at module initialization time were added: -\function{PyModule_AddObject()}, \function{PyModule_AddIntConstant()}, -and \function{PyModule_AddStringConstant()}. Each of these functions -takes a module object, a null-terminated C string containing the name -to be added, and a third argument for the value to be assigned to the -name. This third argument is, respectively, a Python object, a C -long, or a C string. - -A wrapper API was added for Unix-style signal handlers. -\function{PyOS_getsig()} gets a signal handler and -\function{PyOS_setsig()} will set a new handler. - -% ====================================================================== -\section{Distutils: Making Modules Easy to Install} - -Before Python 2.0, installing modules was a tedious affair -- there -was no way to figure out automatically where Python is installed, or -what compiler options to use for extension modules. Software authors -had to go through an arduous ritual of editing Makefiles and -configuration files, which only really work on Unix and leave Windows -and MacOS unsupported. Python users faced wildly differing -installation instructions which varied between different extension -packages, which made adminstering a Python installation something of a -chore. - -The SIG for distribution utilities, shepherded by Greg Ward, has -created the Distutils, a system to make package installation much -easier. They form the \module{distutils} package, a new part of -Python's standard library. In the best case, installing a Python -module from source will require the same steps: first you simply mean -unpack the tarball or zip archive, and the run ``\code{python setup.py -install}''. The platform will be automatically detected, the compiler -will be recognized, C extension modules will be compiled, and the -distribution installed into the proper directory. Optional -command-line arguments provide more control over the installation -process, the distutils package offers many places to override defaults --- separating the build from the install, building or installing in -non-default directories, and more. - -In order to use the Distutils, you need to write a \file{setup.py} -script. For the simple case, when the software contains only .py -files, a minimal \file{setup.py} can be just a few lines long: - -\begin{verbatim} -from distutils.core import setup -setup (name = "foo", version = "1.0", - py_modules = ["module1", "module2"]) -\end{verbatim} - -The \file{setup.py} file isn't much more complicated if the software -consists of a few packages: - -\begin{verbatim} -from distutils.core import setup -setup (name = "foo", version = "1.0", - packages = ["package", "package.subpackage"]) -\end{verbatim} - -A C extension can be the most complicated case; here's an example taken from -the PyXML package: - - -\begin{verbatim} -from distutils.core import setup, Extension - -expat_extension = Extension('xml.parsers.pyexpat', - define_macros = [('XML_NS', None)], - include_dirs = [ 'extensions/expat/xmltok', - 'extensions/expat/xmlparse' ], - sources = [ 'extensions/pyexpat.c', - 'extensions/expat/xmltok/xmltok.c', - 'extensions/expat/xmltok/xmlrole.c', - ] - ) -setup (name = "PyXML", version = "0.5.4", - ext_modules =[ expat_extension ] ) -\end{verbatim} - -The Distutils can also take care of creating source and binary -distributions. The ``sdist'' command, run by ``\code{python setup.py -sdist}', builds a source distribution such as \file{foo-1.0.tar.gz}. -Adding new commands isn't difficult, ``bdist_rpm'' and -``bdist_wininst'' commands have already been contributed to create an -RPM distribution and a Windows installer for the software, -respectively. Commands to create other distribution formats such as -Debian packages and Solaris \file{.pkg} files are in various stages of -development. - -All this is documented in a new manual, \textit{Distributing Python -Modules}, that joins the basic set of Python documentation. - -% ====================================================================== -\section{XML Modules} - -Python 1.5.2 included a simple XML parser in the form of the -\module{xmllib} module, contributed by Sjoerd Mullender. Since -1.5.2's release, two different interfaces for processing XML have -become common: SAX2 (version 2 of the Simple API for XML) provides an -event-driven interface with some similarities to \module{xmllib}, and -the DOM (Document Object Model) provides a tree-based interface, -transforming an XML document into a tree of nodes that can be -traversed and modified. Python 2.0 includes a SAX2 interface and a -stripped-down DOM interface as part of the \module{xml} package. -Here we will give a brief overview of these new interfaces; consult -the Python documentation or the source code for complete details. -The Python XML SIG is also working on improved documentation. - -\subsection{SAX2 Support} - -SAX defines an event-driven interface for parsing XML. To use SAX, -you must write a SAX handler class. Handler classes inherit from -various classes provided by SAX, and override various methods that -will then be called by the XML parser. For example, the -\method{startElement} and \method{endElement} methods are called for -every starting and end tag encountered by the parser, the -\method{characters()} method is called for every chunk of character -data, and so forth. - -The advantage of the event-driven approach is that that the whole -document doesn't have to be resident in memory at any one time, which -matters if you are processing really huge documents. However, writing -the SAX handler class can get very complicated if you're trying to -modify the document structure in some elaborate way. - -For example, this little example program defines a handler that prints -a message for every starting and ending tag, and then parses the file -\file{hamlet.xml} using it: - -\begin{verbatim} -from xml import sax - -class SimpleHandler(sax.ContentHandler): - def startElement(self, name, attrs): - print 'Start of element:', name, attrs.keys() - - def endElement(self, name): - print 'End of element:', name - -# Create a parser object -parser = sax.make_parser() - -# Tell it what handler to use -handler = SimpleHandler() -parser.setContentHandler( handler ) - -# Parse a file! -parser.parse( 'hamlet.xml' ) -\end{verbatim} - -For more information, consult the Python documentation, or the XML -HOWTO at \url{http://www.python.org/doc/howto/xml/}. - -\subsection{DOM Support} - -The Document Object Model is a tree-based representation for an XML -document. A top-level \class{Document} instance is the root of the -tree, and has a single child which is the top-level \class{Element} -instance. This \class{Element} has children nodes representing -character data and any sub-elements, which may have further children -of their own, and so forth. Using the DOM you can traverse the -resulting tree any way you like, access element and attribute values, -insert and delete nodes, and convert the tree back into XML. - -The DOM is useful for modifying XML documents, because you can create -a DOM tree, modify it by adding new nodes or rearranging subtrees, and -then produce a new XML document as output. You can also construct a -DOM tree manually and convert it to XML, which can be a more flexible -way of producing XML output than simply writing -\code{}...\code{} to a file. - -The DOM implementation included with Python lives in the -\module{xml.dom.minidom} module. It's a lightweight implementation of -the Level 1 DOM with support for XML namespaces. The -\function{parse()} and \function{parseString()} convenience -functions are provided for generating a DOM tree: - -\begin{verbatim} -from xml.dom import minidom -doc = minidom.parse('hamlet.xml') -\end{verbatim} - -\code{doc} is a \class{Document} instance. \class{Document}, like all -the other DOM classes such as \class{Element} and \class{Text}, is a -subclass of the \class{Node} base class. All the nodes in a DOM tree -therefore support certain common methods, such as \method{toxml()} -which returns a string containing the XML representation of the node -and its children. Each class also has special methods of its own; for -example, \class{Element} and \class{Document} instances have a method -to find all child elements with a given tag name. Continuing from the -previous 2-line example: - -\begin{verbatim} -perslist = doc.getElementsByTagName( 'PERSONA' ) -print perslist[0].toxml() -print perslist[1].toxml() -\end{verbatim} - -For the \textit{Hamlet} XML file, the above few lines output: - -\begin{verbatim} -CLAUDIUS, king of Denmark. -HAMLET, son to the late, and nephew to the present king. -\end{verbatim} - -The root element of the document is available as -\code{doc.documentElement}, and its children can be easily modified -by deleting, adding, or removing nodes: - -\begin{verbatim} -root = doc.documentElement - -# Remove the first child -root.removeChild( root.childNodes[0] ) - -# Move the new first child to the end -root.appendChild( root.childNodes[0] ) - -# Insert the new first child (originally, -# the third child) before the 20th child. -root.insertBefore( root.childNodes[0], root.childNodes[20] ) -\end{verbatim} - -Again, I will refer you to the Python documentation for a complete -listing of the different \class{Node} classes and their various methods. - -\subsection{Relationship to PyXML} - -The XML Special Interest Group has been working on XML-related Python -code for a while. Its code distribution, called PyXML, is available -from the SIG's Web pages at \url{http://www.python.org/sigs/xml-sig/}. -The PyXML distribution also used the package name \samp{xml}. If -you've written programs that used PyXML, you're probably wondering -about its compatibility with the 2.0 \module{xml} package. - -The answer is that Python 2.0's \module{xml} package isn't compatible -with PyXML, but can be made compatible by installing a recent version -PyXML. Many applications can get by with the XML support that is -included with Python 2.0, but more complicated applications will -require that the full PyXML package will be installed. When -installed, PyXML versions 0.6.0 or greater will replace the -\module{xml} package shipped with Python, and will be a strict -superset of the standard package, adding a bunch of additional -features. Some of the additional features in PyXML include: - -\begin{itemize} -\item 4DOM, a full DOM implementation -from FourThought, Inc. -\item The xmlproc validating parser, written by Lars Marius Garshol. -\item The \module{sgmlop} parser accelerator module, written by Fredrik Lundh. -\end{itemize} - -% ====================================================================== -\section{Module changes} - -Lots of improvements and bugfixes were made to Python's extensive -standard library; some of the affected modules include -\module{readline}, \module{ConfigParser}, \module{cgi}, -\module{calendar}, \module{posix}, \module{readline}, \module{xmllib}, -\module{aifc}, \module{chunk, wave}, \module{random}, \module{shelve}, -and \module{nntplib}. Consult the CVS logs for the exact -patch-by-patch details. - -Brian Gallew contributed OpenSSL support for the \module{socket} -module. OpenSSL is an implementation of the Secure Socket Layer, -which encrypts the data being sent over a socket. When compiling -Python, you can edit \file{Modules/Setup} to include SSL support, -which adds an additional function to the \module{socket} module: -\function{socket.ssl(\var{socket}, \var{keyfile}, \var{certfile})}, -which takes a socket object and returns an SSL socket. The -\module{httplib} and \module{urllib} modules were also changed to -support ``https://'' URLs, though no one has implemented FTP or SMTP -over SSL. - -The \module{httplib} module has been rewritten by Greg Stein to -support HTTP/1.1. Backward compatibility with the 1.5 version of -\module{httplib} is provided, though using HTTP/1.1 features such as -pipelining will require rewriting code to use a different set of -interfaces. - -The \module{Tkinter} module now supports Tcl/Tk version 8.1, 8.2, or -8.3, and support for the older 7.x versions has been dropped. The -Tkinter module now supports displaying Unicode strings in Tk widgets. -Also, Fredrik Lundh contributed an optimization which makes operations -like \code{create_line} and \code{create_polygon} much faster, -especially when using lots of coordinates. - -The \module{curses} module has been greatly extended, starting from -Oliver Andrich's enhanced version, to provide many additional -functions from ncurses and SYSV curses, such as colour, alternative -character set support, pads, and mouse support. This means the module -is no longer compatible with operating systems that only have BSD -curses, but there don't seem to be any currently maintained OSes that -fall into this category. - -As mentioned in the earlier discussion of 2.0's Unicode support, the -underlying implementation of the regular expressions provided by the -\module{re} module has been changed. SRE, a new regular expression -engine written by Fredrik Lundh and partially funded by Hewlett -Packard, supports matching against both 8-bit strings and Unicode -strings. - -% ====================================================================== -\section{New modules} - -A number of new modules were added. We'll simply list them with brief -descriptions; consult the 2.0 documentation for the details of a -particular module. - -\begin{itemize} - -\item{\module{atexit}}: -For registering functions to be called before the Python interpreter exits. -Code that currently sets -\code{sys.exitfunc} directly should be changed to -use the \module{atexit} module instead, importing \module{atexit} -and calling \function{atexit.register()} with -the function to be called on exit. -(Contributed by Skip Montanaro.) - -\item{\module{codecs}, \module{encodings}, \module{unicodedata}:} Added as part of the new Unicode support. - -\item{\module{filecmp}:} Supersedes the old \module{cmp}, \module{cmpcache} and -\module{dircmp} modules, which have now become deprecated. -(Contributed by Gordon MacMillan and Moshe Zadka.) - -\item{\module{gettext}:} This module provides internationalization -(I18N) and localization (L10N) support for Python programs by -providing an interface to the GNU gettext message catalog library. -(Integrated by Barry Warsaw, from separate contributions by Martin von -Loewis, Peter Funk, and James Henstridge.) - -\item{\module{linuxaudiodev}:} Support for the \file{/dev/audio} -device on Linux, a twin to the existing \module{sunaudiodev} module. -(Contributed by Peter Bosch, with fixes by Jeremy Hylton.) - -\item{\module{mmap}:} An interface to memory-mapped files on both -Windows and Unix. A file's contents can be mapped directly into -memory, at which point it behaves like a mutable string, so its -contents can be read and modified. They can even be passed to -functions that expect ordinary strings, such as the \module{re} -module. (Contributed by Sam Rushing, with some extensions by -A.M. Kuchling.) - -\item{\module{pyexpat}:} An interface to the Expat XML parser. -(Contributed by Paul Prescod.) - -\item{\module{robotparser}:} Parse a \file{robots.txt} file, which is -used for writing Web spiders that politely avoid certain areas of a -Web site. The parser accepts the contents of a \file{robots.txt} file, -builds a set of rules from it, and can then answer questions about -the fetchability of a given URL. (Contributed by Skip Montanaro.) - -\item{\module{tabnanny}:} A module/script to -check Python source code for ambiguous indentation. -(Contributed by Tim Peters.) - -\item{\module{UserString}:} A base class useful for deriving objects that behave like strings. - -\item{\module{webbrowser}:} A module that provides a platform independent -way to launch a web browser on a specific URL. For each platform, various -browsers are tried in a specific order. The user can alter which browser -is launched by setting the \var{BROWSER} environment variable. -(Originally inspired by Eric S. Raymond's patch to \module{urllib} -which added similar functionality, but -the final module comes from code originally -implemented by Fred Drake as \file{Tools/idle/BrowserControl.py}, -and adapted for the standard library by Fred.) - -\item{\module{_winreg}:} An interface to the -Windows registry. \module{_winreg} is an adaptation of functions that -have been part of PythonWin since 1995, but has now been added to the core -distribution, and enhanced to support Unicode. -\module{_winreg} was written by Bill Tutt and Mark Hammond. - -\item{\module{zipfile}:} A module for reading and writing ZIP-format -archives. These are archives produced by \program{PKZIP} on -DOS/Windows or \program{zip} on Unix, not to be confused with -\program{gzip}-format files (which are supported by the \module{gzip} -module) -(Contributed by James C. Ahlstrom.) - -\item{\module{imputil}:} A module that provides a simpler way for -writing customised import hooks, in comparison to the existing -\module{ihooks} module. (Implemented by Greg Stein, with much -discussion on python-dev along the way.) - -\end{itemize} - -% ====================================================================== -\section{IDLE Improvements} - -IDLE is the official Python cross-platform IDE, written using Tkinter. -Python 2.0 includes IDLE 0.6, which adds a number of new features and -improvements. A partial list: - -\begin{itemize} -\item UI improvements and optimizations, -especially in the area of syntax highlighting and auto-indentation. - -\item The class browser now shows more information, such as the top -level functions in a module. - -\item Tab width is now a user settable option. When opening an existing Python -file, IDLE automatically detects the indentation conventions, and adapts. - -\item There is now support for calling browsers on various platforms, -used to open the Python documentation in a browser. - -\item IDLE now has a command line, which is largely similar to -the vanilla Python interpreter. - -\item Call tips were added in many places. - -\item IDLE can now be installed as a package. - -\item In the editor window, there is now a line/column bar at the bottom. - -\item Three new keystroke commands: Check module (Alt-F5), Import -module (F5) and Run script (Ctrl-F5). - -\end{itemize} - -% ====================================================================== -\section{Deleted and Deprecated Modules} - -A few modules have been dropped because they're obsolete, or because -there are now better ways to do the same thing. The \module{stdwin} -module is gone; it was for a platform-independent windowing toolkit -that's no longer developed. - -A number of modules have been moved to the -\file{lib-old} subdirectory: -\module{cmp}, \module{cmpcache}, \module{dircmp}, \module{dump}, -\module{find}, \module{grep}, \module{packmail}, -\module{poly}, \module{util}, \module{whatsound}, \module{zmod}. -If you have code which relies on a module that's been moved to -\file{lib-old}, you can simply add that directory to \code{sys.path} -to get them back, but you're encouraged to update any code that uses -these modules. - -\section{Acknowledgements} - -The authors would like to thank the following people for offering -suggestions on various drafts of this article: David Bolen, Mark Hammond, Gregg Hauser, -Jeremy Hylton, Fredrik Lundh, Detlef Lannert, Aahz Maruch, Skip -Montanaro, Vladimir Marangozov, Guido van Rossum, Neil Schemenauer, -and Russ Schmidt. - -\end{document} diff --git a/Doc/whatsnew/whatsnew21.tex b/Doc/whatsnew/whatsnew21.tex deleted file mode 100644 index 04e8ff192a..0000000000 --- a/Doc/whatsnew/whatsnew21.tex +++ /dev/null @@ -1,874 +0,0 @@ -\documentclass{howto} - -\usepackage{distutils} - -% $Id$ - -\title{What's New in Python 2.1} -\release{0.99} -\author{A.M. Kuchling} -\authoraddress{\email{amk1@bigfoot.com}} -\begin{document} -\maketitle\tableofcontents - -\section{Introduction} - -{\large This document is a draft, and is subject to change until the -final version of Python 2.1 is released. Currently it is up to date -for Python 2.1 release candidate~1. Please send any comments, bug -reports, or questions, no matter how minor, to -\email{amk1@bigfoot.com}. } - -It's that time again... time for a new Python release, Python 2.1. -One recent goal of the Python development team has been to accelerate -the pace of new releases, with a new release coming every 6 to 9 -months. 2.1 is the first release to come out at this faster pace, with -the first alpha appearing in January, 3 months after the final version -of 2.0 was released. - -This article explains the new features in 2.1. While there aren't as -many changes in 2.1 as there were in Python 2.0, there are still some -pleasant surprises in store. 2.1 is the first release to be steered -through the use of Python Enhancement Proposals, or PEPs, so most of -the sizable changes have accompanying PEPs that provide more complete -documentation and a design rationale for the change. This article -doesn't attempt to document the new features completely, but simply -provides an overview of the new features for Python programmers. -Refer to the Python 2.1 documentation, or to the specific PEP, for -more details about any new feature that particularly interests you. - -The final release of Python 2.1 is planned for April 2001. - -%====================================================================== -\section{PEP 227: Nested Scopes} - -The largest change in Python 2.1 is to Python's scoping rules. In -Python 2.0, at any given time there are at most three namespaces used -to look up variable names: local, module-level, and the built-in -namespace. This often surprised people because it didn't match their -intuitive expectations. For example, a nested recursive function -definition doesn't work: - -\begin{verbatim} -def f(): - ... - def g(value): - ... - return g(value-1) + 1 - ... -\end{verbatim} - -The function \function{g()} will always raise a \exception{NameError} -exception, because the binding of the name \samp{g} isn't in either -its local namespace or in the module-level namespace. This isn't much -of a problem in practice (how often do you recursively define interior -functions like this?), but this also made using the \keyword{lambda} -statement clumsier, and this was a problem in practice. In code which -uses \keyword{lambda} you can often find local variables being copied -by passing them as the default values of arguments. - -\begin{verbatim} -def find(self, name): - "Return list of any entries equal to 'name'" - L = filter(lambda x, name=name: x == name, - self.list_attribute) - return L -\end{verbatim} - -The readability of Python code written in a strongly functional style -suffers greatly as a result. - -The most significant change to Python 2.1 is that static scoping has -been added to the language to fix this problem. As a first effect, -the \code{name=name} default argument is now unnecessary in the above -example. Put simply, when a given variable name is not assigned a -value within a function (by an assignment, or the \keyword{def}, -\keyword{class}, or \keyword{import} statements), references to the -variable will be looked up in the local namespace of the enclosing -scope. A more detailed explanation of the rules, and a dissection of -the implementation, can be found in the PEP. - -This change may cause some compatibility problems for code where the -same variable name is used both at the module level and as a local -variable within a function that contains further function definitions. -This seems rather unlikely though, since such code would have been -pretty confusing to read in the first place. - -One side effect of the change is that the \code{from \var{module} -import *} and \keyword{exec} statements have been made illegal inside -a function scope under certain conditions. The Python reference -manual has said all along that \code{from \var{module} import *} is -only legal at the top level of a module, but the CPython interpreter -has never enforced this before. As part of the implementation of -nested scopes, the compiler which turns Python source into bytecodes -has to generate different code to access variables in a containing -scope. \code{from \var{module} import *} and \keyword{exec} make it -impossible for the compiler to figure this out, because they add names -to the local namespace that are unknowable at compile time. -Therefore, if a function contains function definitions or -\keyword{lambda} expressions with free variables, the compiler will -flag this by raising a \exception{SyntaxError} exception. - -To make the preceding explanation a bit clearer, here's an example: - -\begin{verbatim} -x = 1 -def f(): - # The next line is a syntax error - exec 'x=2' - def g(): - return x -\end{verbatim} - -Line 4 containing the \keyword{exec} statement is a syntax error, -since \keyword{exec} would define a new local variable named \samp{x} -whose value should be accessed by \function{g()}. - -This shouldn't be much of a limitation, since \keyword{exec} is rarely -used in most Python code (and when it is used, it's often a sign of a -poor design anyway). - -Compatibility concerns have led to nested scopes being introduced -gradually; in Python 2.1, they aren't enabled by default, but can be -turned on within a module by using a future statement as described in -PEP 236. (See the following section for further discussion of PEP -236.) In Python 2.2, nested scopes will become the default and there -will be no way to turn them off, but users will have had all of 2.1's -lifetime to fix any breakage resulting from their introduction. - -\begin{seealso} - -\seepep{227}{Statically Nested Scopes}{Written and implemented by -Jeremy Hylton.} - -\end{seealso} - - -%====================================================================== -\section{PEP 236: \module{__future__} Directives} - -The reaction to nested scopes was widespread concern about the dangers -of breaking code with the 2.1 release, and it was strong enough to -make the Pythoneers take a more conservative approach. This approach -consists of introducing a convention for enabling optional -functionality in release N that will become compulsory in release N+1. - -The syntax uses a \code{from...import} statement using the reserved -module name \module{__future__}. Nested scopes can be enabled by the -following statement: - -\begin{verbatim} -from __future__ import nested_scopes -\end{verbatim} - -While it looks like a normal \keyword{import} statement, it's not; -there are strict rules on where such a future statement can be put. -They can only be at the top of a module, and must precede any Python -code or regular \keyword{import} statements. This is because such -statements can affect how the Python bytecode compiler parses code and -generates bytecode, so they must precede any statement that will -result in bytecodes being produced. - -\begin{seealso} - -\seepep{236}{Back to the \module{__future__}}{Written by Tim Peters, -and primarily implemented by Jeremy Hylton.} - -\end{seealso} - -%====================================================================== -\section{PEP 207: Rich Comparisons} - -In earlier versions, Python's support for implementing comparisons on -user-defined classes and extension types was quite simple. Classes -could implement a \method{__cmp__} method that was given two instances -of a class, and could only return 0 if they were equal or +1 or -1 if -they weren't; the method couldn't raise an exception or return -anything other than a Boolean value. Users of Numeric Python often -found this model too weak and restrictive, because in the -number-crunching programs that numeric Python is used for, it would be -more useful to be able to perform elementwise comparisons of two -matrices, returning a matrix containing the results of a given -comparison for each element. If the two matrices are of different -sizes, then the compare has to be able to raise an exception to signal -the error. - -In Python 2.1, rich comparisons were added in order to support this -need. Python classes can now individually overload each of the -\code{<}, \code{<=}, \code{>}, \code{>=}, \code{==}, and \code{!=} -operations. The new magic method names are: - -\begin{tableii}{c|l}{code}{Operation}{Method name} - \lineii{<}{\method{__lt__}} \lineii{<=}{\method{__le__}} - \lineii{>}{\method{__gt__}} \lineii{>=}{\method{__ge__}} - \lineii{==}{\method{__eq__}} \lineii{!=}{\method{__ne__}} - \end{tableii} - -(The magic methods are named after the corresponding Fortran operators -\code{.LT.}. \code{.LE.}, \&c. Numeric programmers are almost -certainly quite familar with these names and will find them easy to -remember.) - -Each of these magic methods is of the form \code{\var{method}(self, -other)}, where \code{self} will be the object on the left-hand side of -the operator, while \code{other} will be the object on the right-hand -side. For example, the expression \code{A < B} will cause -\code{A.__lt__(B)} to be called. - -Each of these magic methods can return anything at all: a Boolean, a -matrix, a list, or any other Python object. Alternatively they can -raise an exception if the comparison is impossible, inconsistent, or -otherwise meaningless. - -The built-in \function{cmp(A,B)} function can use the rich comparison -machinery, and now accepts an optional argument specifying which -comparison operation to use; this is given as one of the strings -\code{"<"}, \code{"<="}, \code{">"}, \code{">="}, \code{"=="}, or -\code{"!="}. If called without the optional third argument, -\function{cmp()} will only return -1, 0, or +1 as in previous versions -of Python; otherwise it will call the appropriate method and can -return any Python object. - -There are also corresponding changes of interest to C programmers; -there's a new slot \code{tp_richcmp} in type objects and an API for -performing a given rich comparison. I won't cover the C API here, but -will refer you to PEP 207, or to 2.1's C API documentation, for the -full list of related functions. - -\begin{seealso} - -\seepep{207}{Rich Comparisions}{Written by Guido van Rossum, heavily -based on earlier work by David Ascher, and implemented by Guido van -Rossum.} - -\end{seealso} - -%====================================================================== -\section{PEP 230: Warning Framework} - -Over its 10 years of existence, Python has accumulated a certain -number of obsolete modules and features along the way. It's difficult -to know when a feature is safe to remove, since there's no way of -knowing how much code uses it --- perhaps no programs depend on the -feature, or perhaps many do. To enable removing old features in a -more structured way, a warning framework was added. When the Python -developers want to get rid of a feature, it will first trigger a -warning in the next version of Python. The following Python version -can then drop the feature, and users will have had a full release -cycle to remove uses of the old feature. - -Python 2.1 adds the warning framework to be used in this scheme. It -adds a \module{warnings} module that provide functions to issue -warnings, and to filter out warnings that you don't want to be -displayed. Third-party modules can also use this framework to -deprecate old features that they no longer wish to support. - -For example, in Python 2.1 the \module{regex} module is deprecated, so -importing it causes a warning to be printed: - -\begin{verbatim} ->>> import regex -__main__:1: DeprecationWarning: the regex module - is deprecated; please use the re module ->>> -\end{verbatim} - -Warnings can be issued by calling the \function{warnings.warn} -function: - -\begin{verbatim} -warnings.warn("feature X no longer supported") -\end{verbatim} - -The first parameter is the warning message; an additional optional -parameters can be used to specify a particular warning category. - -Filters can be added to disable certain warnings; a regular expression -pattern can be applied to the message or to the module name in order -to suppress a warning. For example, you may have a program that uses -the \module{regex} module and not want to spare the time to convert it -to use the \module{re} module right now. The warning can be -suppressed by calling - -\begin{verbatim} -import warnings -warnings.filterwarnings(action = 'ignore', - message='.*regex module is deprecated', - category=DeprecationWarning, - module = '__main__') -\end{verbatim} - -This adds a filter that will apply only to warnings of the class -\class{DeprecationWarning} triggered in the \module{__main__} module, -and applies a regular expression to only match the message about the -\module{regex} module being deprecated, and will cause such warnings -to be ignored. Warnings can also be printed only once, printed every -time the offending code is executed, or turned into exceptions that -will cause the program to stop (unless the exceptions are caught in -the usual way, of course). - -Functions were also added to Python's C API for issuing warnings; -refer to PEP 230 or to Python's API documentation for the details. - -\begin{seealso} - -\seepep{5}{Guidelines for Language Evolution}{Written -by Paul Prescod, to specify procedures to be followed when removing -old features from Python. The policy described in this PEP hasn't -been officially adopted, but the eventual policy probably won't be too -different from Prescod's proposal.} - -\seepep{230}{Warning Framework}{Written and implemented by Guido van -Rossum.} - -\end{seealso} - -%====================================================================== -\section{PEP 229: New Build System} - -When compiling Python, the user had to go in and edit the -\file{Modules/Setup} file in order to enable various additional -modules; the default set is relatively small and limited to modules -that compile on most Unix platforms. This means that on Unix -platforms with many more features, most notably Linux, Python -installations often don't contain all useful modules they could. - -Python 2.0 added the Distutils, a set of modules for distributing and -installing extensions. In Python 2.1, the Distutils are used to -compile much of the standard library of extension modules, -autodetecting which ones are supported on the current machine. It's -hoped that this will make Python installations easier and more -featureful. - -Instead of having to edit the \file{Modules/Setup} file in order to -enable modules, a \file{setup.py} script in the top directory of the -Python source distribution is run at build time, and attempts to -discover which modules can be enabled by examining the modules and -header files on the system. If a module is configured in -\file{Modules/Setup}, the \file{setup.py} script won't attempt to -compile that module and will defer to the \file{Modules/Setup} file's -contents. This provides a way to specific any strange command-line -flags or libraries that are required for a specific platform. - -In another far-reaching change to the build mechanism, Neil -Schemenauer restructured things so Python now uses a single makefile -that isn't recursive, instead of makefiles in the top directory and in -each of the \file{Python/}, \file{Parser/}, \file{Objects/}, and -\file{Modules/} subdirectories. This makes building Python faster -and also makes hacking the Makefiles clearer and simpler. - -\begin{seealso} - -\seepep{229}{Using Distutils to Build Python}{Written -and implemented by A.M. Kuchling.} - -\end{seealso} - -%====================================================================== -\section{PEP 205: Weak References} - -Weak references, available through the \module{weakref} module, are a -minor but useful new data type in the Python programmer's toolbox. - -Storing a reference to an object (say, in a dictionary or a list) has -the side effect of keeping that object alive forever. There are a few -specific cases where this behaviour is undesirable, object caches -being the most common one, and another being circular references in -data structures such as trees. - -For example, consider a memoizing function that caches the results of -another function \function{f(\var{x})} by storing the function's -argument and its result in a dictionary: - -\begin{verbatim} -_cache = {} -def memoize(x): - if _cache.has_key(x): - return _cache[x] - - retval = f(x) - - # Cache the returned object - _cache[x] = retval - - return retval -\end{verbatim} - -This version works for simple things such as integers, but it has a -side effect; the \code{_cache} dictionary holds a reference to the -return values, so they'll never be deallocated until the Python -process exits and cleans up This isn't very noticeable for integers, -but if \function{f()} returns an object, or a data structure that -takes up a lot of memory, this can be a problem. - -Weak references provide a way to implement a cache that won't keep -objects alive beyond their time. If an object is only accessible -through weak references, the object will be deallocated and the weak -references will now indicate that the object it referred to no longer -exists. A weak reference to an object \var{obj} is created by calling -\code{wr = weakref.ref(\var{obj})}. The object being referred to is -returned by calling the weak reference as if it were a function: -\code{wr()}. It will return the referenced object, or \code{None} if -the object no longer exists. - -This makes it possible to write a \function{memoize()} function whose -cache doesn't keep objects alive, by storing weak references in the -cache. - -\begin{verbatim} -_cache = {} -def memoize(x): - if _cache.has_key(x): - obj = _cache[x]() - # If weak reference object still exists, - # return it - if obj is not None: return obj - - retval = f(x) - - # Cache a weak reference - _cache[x] = weakref.ref(retval) - - return retval -\end{verbatim} - -The \module{weakref} module also allows creating proxy objects which -behave like weak references --- an object referenced only by proxy -objects is deallocated -- but instead of requiring an explicit call to -retrieve the object, the proxy transparently forwards all operations -to the object as long as the object still exists. If the object is -deallocated, attempting to use a proxy will cause a -\exception{weakref.ReferenceError} exception to be raised. - -\begin{verbatim} -proxy = weakref.proxy(obj) -proxy.attr # Equivalent to obj.attr -proxy.meth() # Equivalent to obj.meth() -del obj -proxy.attr # raises weakref.ReferenceError -\end{verbatim} - -\begin{seealso} - -\seepep{205}{Weak References}{Written and implemented by -Fred~L. Drake,~Jr.} - -\end{seealso} - -%====================================================================== -\section{PEP 232: Function Attributes} - -In Python 2.1, functions can now have arbitrary information attached -to them. People were often using docstrings to hold information about -functions and methods, because the \code{__doc__} attribute was the -only way of attaching any information to a function. For example, in -the Zope Web application server, functions are marked as safe for -public access by having a docstring, and in John Aycock's SPARK -parsing framework, docstrings hold parts of the BNF grammar to be -parsed. This overloading is unfortunate, since docstrings are really -intended to hold a function's documentation; for example, it means you -can't properly document functions intended for private use in Zope. - -Arbitrary attributes can now be set and retrieved on functions using the -regular Python syntax: - -\begin{verbatim} -def f(): pass - -f.publish = 1 -f.secure = 1 -f.grammar = "A ::= B (C D)*" -\end{verbatim} - -The dictionary containing attributes can be accessed as the function's -\member{__dict__}. Unlike the \member{__dict__} attribute of class -instances, in functions you can actually assign a new dictionary to -\member{__dict__}, though the new value is restricted to a regular -Python dictionary; you \emph{can't} be tricky and set it to a -\class{UserDict} instance, or any other random object that behaves -like a mapping. - -\begin{seealso} - -\seepep{232}{Function Attributes}{Written and implemented by Barry -Warsaw.} - -\end{seealso} - - -%====================================================================== - -\section{PEP 235: Case-Insensitive Platforms and \keyword{import}} - -Some operating systems have filesystems that are case-insensitive, -MacOS and Windows being the primary examples; on these systems, it's -impossible to distinguish the filenames \samp{FILE.PY} and -\samp{file.py}, even though they do store the file's name -in its original case (they're case-preserving, too). - -In Python 2.1, the \keyword{import} statement will work to simulate -case-sensitivity on case-insensitive platforms. Python will now -search for the first case-sensitive match by default, raising an -\exception{ImportError} if no such file is found, so \code{import file} -will not import a module named \samp{FILE.PY}. Case-insensitive -matching can be requested by setting the \envvar{PYTHONCASEOK} environment -variable before starting the Python interpreter. - -%====================================================================== -\section{PEP 217: Interactive Display Hook} - -When using the Python interpreter interactively, the output of -commands is displayed using the built-in \function{repr()} function. -In Python 2.1, the variable \function{sys.displayhook} can be set to a -callable object which will be called instead of \function{repr()}. -For example, you can set it to a special pretty-printing function: - -\begin{verbatim} ->>> # Create a recursive data structure -... L = [1,2,3] ->>> L.append(L) ->>> L # Show Python's default output -[1, 2, 3, [...]] ->>> # Use pprint.pprint() as the display function -... import sys, pprint ->>> sys.displayhook = pprint.pprint ->>> L -[1, 2, 3, ] ->>> -\end{verbatim} - -\begin{seealso} - -\seepep{217}{Display Hook for Interactive Use}{Written and implemented -by Moshe Zadka.} - -\end{seealso} - -%====================================================================== -\section{PEP 208: New Coercion Model} - -How numeric coercion is done at the C level was significantly -modified. This will only affect the authors of C extensions to -Python, allowing them more flexibility in writing extension types that -support numeric operations. - -Extension types can now set the type flag \code{Py_TPFLAGS_CHECKTYPES} -in their \code{PyTypeObject} structure to indicate that they support -the new coercion model. In such extension types, the numeric slot -functions can no longer assume that they'll be passed two arguments of -the same type; instead they may be passed two arguments of differing -types, and can then perform their own internal coercion. If the slot -function is passed a type it can't handle, it can indicate the failure -by returning a reference to the \code{Py_NotImplemented} singleton -value. The numeric functions of the other type will then be tried, -and perhaps they can handle the operation; if the other type also -returns \code{Py_NotImplemented}, then a \exception{TypeError} will be -raised. Numeric methods written in Python can also return -\code{Py_NotImplemented}, causing the interpreter to act as if the -method did not exist (perhaps raising a \exception{TypeError}, perhaps -trying another object's numeric methods). - -\begin{seealso} - -\seepep{208}{Reworking the Coercion Model}{Written and implemented by -Neil Schemenauer, heavily based upon earlier work by Marc-Andr\'e -Lemburg. Read this to understand the fine points of how numeric -operations will now be processed at the C level.} - -\end{seealso} - -%====================================================================== -\section{PEP 241: Metadata in Python Packages} - -A common complaint from Python users is that there's no single catalog -of all the Python modules in existence. T.~Middleton's Vaults of -Parnassus at \url{http://www.vex.net/parnassus} are the largest -catalog of Python modules, but registering software at the Vaults is -optional, and many people don't bother. - -As a first small step toward fixing the problem, Python software -packaged using the Distutils \command{sdist} command will include a -file named \file{PKG-INFO} containing information about the package -such as its name, version, and author (metadata, in cataloguing -terminology). PEP 241 contains the full list of fields that can be -present in the \file{PKG-INFO} file. As people began to package their -software using Python 2.1, more and more packages will include -metadata, making it possible to build automated cataloguing systems -and experiment with them. With the result experience, perhaps it'll -be possible to design a really good catalog and then build support for -it into Python 2.2. For example, the Distutils \command{sdist} -and \command{bdist_*} commands could support a \option{upload} option -that would automatically upload your package to a catalog server. - -You can start creating packages containing \file{PKG-INFO} even if -you're not using Python 2.1, since a new release of the Distutils will -be made for users of earlier Python versions. Version 1.0.2 of the -Distutils includes the changes described in PEP 241, as well as -various bugfixes and enhancements. It will be available from -the Distutils SIG at \url{http://www.python.org/sigs/distutils-sig}. - -% XXX update when I actually release 1.0.2 - -\begin{seealso} - -\seepep{241}{Metadata for Python Software Packages}{Written and -implemented by A.M. Kuchling.} - -\seepep{243}{Module Repository Upload Mechanism}{Written by Sean -Reifschneider, this draft PEP describes a proposed mechanism for uploading -Python packages to a central server. -} - -\end{seealso} - -%====================================================================== -\section{New and Improved Modules} - -\begin{itemize} - -\item Ka-Ping Yee contributed two new modules: \module{inspect.py}, a -module for getting information about live Python code, and -\module{pydoc.py}, a module for interactively converting docstrings to -HTML or text. As a bonus, \file{Tools/scripts/pydoc}, which is now -automatically installed, uses \module{pydoc.py} to display -documentation given a Python module, package, or class name. For -example, \samp{pydoc xml.dom} displays the following: - -\begin{verbatim} -Python Library Documentation: package xml.dom in xml - -NAME - xml.dom - W3C Document Object Model implementation for Python. - -FILE - /usr/local/lib/python2.1/xml/dom/__init__.pyc - -DESCRIPTION - The Python mapping of the Document Object Model is documented in the - Python Library Reference in the section on the xml.dom package. - - This package contains the following modules: - ... -\end{verbatim} - -\file{pydoc} also includes a Tk-based interactive help browser. -\file{pydoc} quickly becomes addictive; try it out! - -\item Two different modules for unit testing were added to the -standard library. The \module{doctest} module, contributed by Tim -Peters, provides a testing framework based on running embedded -examples in docstrings and comparing the results against the expected -output. PyUnit, contributed by Steve Purcell, is a unit testing -framework inspired by JUnit, which was in turn an adaptation of Kent -Beck's Smalltalk testing framework. See -\url{http://pyunit.sourceforge.net/} for more information about -PyUnit. - -\item The \module{difflib} module contains a class, -\class{SequenceMatcher}, which compares two sequences and computes the -changes required to transform one sequence into the other. For -example, this module can be used to write a tool similar to the Unix -\program{diff} program, and in fact the sample program -\file{Tools/scripts/ndiff.py} demonstrates how to write such a script. - -\item \module{curses.panel}, a wrapper for the panel library, part of -ncurses and of SYSV curses, was contributed by Thomas Gellekum. The -panel library provides windows with the additional feature of depth. -Windows can be moved higher or lower in the depth ordering, and the -panel library figures out where panels overlap and which sections are -visible. - -\item The PyXML package has gone through a few releases since Python -2.0, and Python 2.1 includes an updated version of the \module{xml} -package. Some of the noteworthy changes include support for Expat 1.2 -and later versions, the ability for Expat parsers to handle files in -any encoding supported by Python, and various bugfixes for SAX, DOM, -and the \module{minidom} module. - -\item Ping also contributed another hook for handling uncaught -exceptions. \function{sys.excepthook} can be set to a callable -object. When an exception isn't caught by any -\keyword{try}...\keyword{except} blocks, the exception will be passed -to \function{sys.excepthook}, which can then do whatever it likes. At -the Ninth Python Conference, Ping demonstrated an application for this -hook: printing an extended traceback that not only lists the stack -frames, but also lists the function arguments and the local variables -for each frame. - -\item Various functions in the \module{time} module, such as -\function{asctime()} and \function{localtime()}, require a floating -point argument containing the time in seconds since the epoch. The -most common use of these functions is to work with the current time, -so the floating point argument has been made optional; when a value -isn't provided, the current time will be used. For example, log file -entries usually need a string containing the current time; in Python -2.1, \code{time.asctime()} can be used, instead of the lengthier -\code{time.asctime(time.localtime(time.time()))} that was previously -required. - -This change was proposed and implemented by Thomas Wouters. - -\item The \module{ftplib} module now defaults to retrieving files in -passive mode, because passive mode is more likely to work from behind -a firewall. This request came from the Debian bug tracking system, -since other Debian packages use \module{ftplib} to retrieve files and -then don't work from behind a firewall. It's deemed unlikely that -this will cause problems for anyone, because Netscape defaults to -passive mode and few people complain, but if passive mode is -unsuitable for your application or network setup, call -\method{set_pasv(0)} on FTP objects to disable passive mode. - -\item Support for raw socket access has been added to the -\module{socket} module, contributed by Grant Edwards. - -\item The \module{pstats} module now contains a simple interactive -statistics browser for displaying timing profiles for Python programs, -invoked when the module is run as a script. Contributed by -Eric S.\ Raymond. - -\item A new implementation-dependent function, \function{sys._getframe(\optional{depth})}, -has been added to return a given frame object from the current call stack. -\function{sys._getframe()} returns the frame at the top of the call stack; -if the optional integer argument \var{depth} is supplied, the function returns the frame -that is \var{depth} calls below the top of the stack. For example, \code{sys._getframe(1)} -returns the caller's frame object. - -This function is only present in CPython, not in Jython or the .NET -implementation. Use it for debugging, and resist the temptation to -put it into production code. - - - -\end{itemize} - -%====================================================================== -\section{Other Changes and Fixes} - -There were relatively few smaller changes made in Python 2.1 due to -the shorter release cycle. A search through the CVS change logs turns -up 117 patches applied, and 136 bugs fixed; both figures are likely to -be underestimates. Some of the more notable changes are: - -\begin{itemize} - - -\item A specialized object allocator is now optionally available, that -should be faster than the system \function{malloc()} and have less -memory overhead. The allocator uses C's \function{malloc()} function -to get large pools of memory, and then fulfills smaller memory -requests from these pools. It can be enabled by providing the -\longprogramopt{with-pymalloc} option to the \program{configure} script; see -\file{Objects/obmalloc.c} for the implementation details. - -Authors of C extension modules should test their code with the object -allocator enabled, because some incorrect code may break, causing core -dumps at runtime. There are a bunch of memory allocation functions in -Python's C API that have previously been just aliases for the C -library's \function{malloc()} and \function{free()}, meaning that if -you accidentally called mismatched functions, the error wouldn't be -noticeable. When the object allocator is enabled, these functions -aren't aliases of \function{malloc()} and \function{free()} any more, -and calling the wrong function to free memory will get you a core -dump. For example, if memory was allocated using -\function{PyMem_New()}, it has to be freed using -\function{PyMem_Del()}, not \function{free()}. A few modules included -with Python fell afoul of this and had to be fixed; doubtless there -are more third-party modules that will have the same problem. - -The object allocator was contributed by Vladimir Marangozov. - -\item The speed of line-oriented file I/O has been improved because -people often complain about its lack of speed, and because it's often -been used as a na\"ive benchmark. The \method{readline()} method of -file objects has therefore been rewritten to be much faster. The -exact amount of the speedup will vary from platform to platform -depending on how slow the C library's \function{getc()} was, but is -around 66\%, and potentially much faster on some particular operating -systems. Tim Peters did much of the benchmarking and coding for this -change, motivated by a discussion in comp.lang.python. - -A new module and method for file objects was also added, contributed -by Jeff Epler. The new method, \method{xreadlines()}, is similar to -the existing \function{xrange()} built-in. \function{xreadlines()} -returns an opaque sequence object that only supports being iterated -over, reading a line on every iteration but not reading the entire -file into memory as the existing \method{readlines()} method does. -You'd use it like this: - -\begin{verbatim} -for line in sys.stdin.xreadlines(): - # ... do something for each line ... - ... -\end{verbatim} - -For a fuller discussion of the line I/O changes, see the python-dev -summary for January 1-15, 2001 at -\url{http://www.amk.ca/python/dev/2001-01-1.html}. - -\item A new method, \method{popitem()}, was added to dictionaries to -enable destructively iterating through the contents of a dictionary; -this can be faster for large dictionaries because there's no need to -construct a list containing all the keys or values. -\code{D.popitem()} removes a random \code{(\var{key}, \var{value})} -pair from the dictionary~\code{D} and returns it as a 2-tuple. This -was implemented mostly by Tim Peters and Guido van Rossum, after a -suggestion and preliminary patch by Moshe Zadka. - -\item Modules can now control which names are imported when \code{from -\var{module} import *} is used, by defining an \code{__all__} -attribute containing a list of names that will be imported. One -common complaint is that if the module imports other modules such as -\module{sys} or \module{string}, \code{from \var{module} import *} -will add them to the importing module's namespace. To fix this, -simply list the public names in \code{__all__}: - -\begin{verbatim} -# List public names -__all__ = ['Database', 'open'] -\end{verbatim} - -A stricter version of this patch was first suggested and implemented -by Ben Wolfson, but after some python-dev discussion, a weaker final -version was checked in. - -\item Applying \function{repr()} to strings previously used octal -escapes for non-printable characters; for example, a newline was -\code{'\e 012'}. This was a vestigial trace of Python's C ancestry, but -today octal is of very little practical use. Ka-Ping Yee suggested -using hex escapes instead of octal ones, and using the \code{\e n}, -\code{\e t}, \code{\e r} escapes for the appropriate characters, and -implemented this new formatting. - -\item Syntax errors detected at compile-time can now raise exceptions -containing the filename and line number of the error, a pleasant side -effect of the compiler reorganization done by Jeremy Hylton. - -\item C extensions which import other modules have been changed to use -\function{PyImport_ImportModule()}, which means that they will use any -import hooks that have been installed. This is also encouraged for -third-party extensions that need to import some other module from C -code. - -\item The size of the Unicode character database was shrunk by another -340K thanks to Fredrik Lundh. - -\item Some new ports were contributed: MacOS X (by Steven Majewski), -Cygwin (by Jason Tishler); RISCOS (by Dietmar Schwertberger); Unixware~7 -(by Billy G. Allie). - -\end{itemize} - -And there's the usual list of minor bugfixes, minor memory leaks, -docstring edits, and other tweaks, too lengthy to be worth itemizing; -see the CVS logs for the full details if you want them. - - -%====================================================================== -\section{Acknowledgements} - -The author would like to thank the following people for offering -suggestions on various drafts of this article: Graeme Cross, David -Goodger, Jay Graves, Michael Hudson, Marc-Andr\'e Lemburg, Fredrik -Lundh, Neil Schemenauer, Thomas Wouters. - -\end{document} diff --git a/Include/config.h b/Include/config.h deleted file mode 100755 index 3f486fff58..0000000000 --- a/Include/config.h +++ /dev/null @@ -1,82 +0,0 @@ -/* Include/config.h. Generated automatically by configure. */ -/* NOTE: config.h.in is converted into config.h by the configure - script in the toplevel directory. - - On non-UNIX systems, manually copy config.h.in to config.h, and - edit the latter to reflect the actual configuration of your system. - - Then arrange that the symbol HAVE_CONFIG_H is defined during - compilation (usually by passing an argument of the form - `-DHAVE_CONFIG_H' to the compiler, but this is necessarily - system-dependent). */ - - -/* Types which have no traditional name -- edit the definition if necessary */ - -#define RETSIGTYPE void /* int or void: return of signal handlers */ - - -/* Types which are often defined in -- either define as - some variant of int or leave undefined. Uncomment a definition if - your does not define the type */ - -/* #define mode_t int */ -/* #define off_t long */ -/* #define pid_t int */ -/* #define size_t unsigned */ -/* #define uid_t int */ -/* #define gid_t int */ - - -/* Feature test symbols -- either define as 1 or leave undefined */ - -/* symbol name: #define as 1 if: */ - -/* #undef STDC_HEADERS */ /* the standard C header files exist - (in particular, , - , and ) */ - -/* #undef HAVE_DLFCN_H */ /* exists */ -#define HAVE_SIGNAL_H 1 /* exists */ -#define HAVE_STDARG_H 1 /* exists (else need ) */ -#define HAVE_STDLIB_H 1 /* exists */ -#define HAVE_UNISTD_H 1 /* exists */ -#define HAVE_UTIME_H 1 /* exists */ - -#define HAVE_SYS_PARAM_H 1 /* exists */ -/* #undef HAVE_SYS_SELECT_H */ /* exists */ -#define HAVE_SYS_TIMES_H 1 /* exists */ -/* #undef HAVE_SYS_TIME_H */ /* exists */ -#define HAVE_SYS_UTSNAME_H 1 /* exists */ - -#define TIME_WITH_SYS_TIME 1 /* and can be included - together */ - -/* #undef HAVE_TM_ZONE */ /* struct tm has a tm_zone member */ -#define HAVE_TZNAME 1 /* extern char *tzname[] exists */ - -#define HAVE_CLOCK 1 /* clock() exists */ -/* #undef HAVE_FTIME */ /* ftime() exists */ -#define HAVE_GETPGRP 1 /* getpgrp() exists */ -#define HAVE_GETTIMEOFDAY 1 /* gettimeofday() exists */ -#define HAVE_LSTAT 1 /* lstat() exists */ -#define HAVE_PROTOTYPES 1 /* the compiler understands prototypes */ -#define HAVE_READLINK 1 /* readlink() exists */ -#define HAVE_SELECT 1 /* select() exists */ -#define HAVE_SETPGID 1 /* setpgid() exists */ -#define HAVE_SETPGRP 1 /* setpgrp() exists */ -#define HAVE_SETSID 1 /* setsid() exists */ -#define HAVE_SYMLINK 1 /* symlink() exists */ -/* #undef HAVE_SIGINTERRUPT */ /* siginterrupt() exists */ -#define HAVE_TCGETPGRP 1 /* tcgetpgrp() exists */ -#define HAVE_TCSETPGRP 1 /* tcsetpgrp() exists */ -#define HAVE_TIMES 1 /* times() exists */ -#define HAVE_UNAME 1 /* uname() exists */ -#define HAVE_WAITPID 1 /* waitpid() exists */ - -/* #undef GETPGRP_HAVE_ARG */ /* getpgrp() must be called as getpgrp(0) - (and setpgrp() as setpgrp(0, 0)) */ - -#define WITH_READLINE 1 /* GNU readline() should be used */ -/* #undef USE_THREAD */ /* Build in thread support */ -/* #undef SOLARIS */ /* This is SOLARIS 2.x */ diff --git a/Include/patchlevel.h b/Include/patchlevel.h index f114bae6b7..675cba2a5b 100644 --- a/Include/patchlevel.h +++ b/Include/patchlevel.h @@ -21,15 +21,15 @@ /* Version parsed out into numeric values */ #define PY_MAJOR_VERSION 2 #define PY_MINOR_VERSION 1 -#define PY_MICRO_VERSION 0 +#define PY_MICRO_VERSION 2 #define PY_RELEASE_LEVEL PY_RELEASE_LEVEL_FINAL #define PY_RELEASE_SERIAL 0 /* Version as a string */ -#define PY_VERSION "2.1" +#define PY_VERSION "2.1.2" /* Historic */ -#define PATCHLEVEL "2.1" +#define PATCHLEVEL "2.1.2" /* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2. Use this for numeric comparisons, e.g. #if PY_VERSION_HEX >= ... */ diff --git a/Include/pyport.h b/Include/pyport.h index 852efb894f..2a59fa1fbf 100644 --- a/Include/pyport.h +++ b/Include/pyport.h @@ -434,6 +434,15 @@ typedef struct fd_set { #endif #endif +/* + * Rename some functions for the Borland compiler + */ +#ifdef __BORLANDC__ +# include +# define _chsize chsize +# define _setmode setmode +#endif + #ifdef __cplusplus } #endif diff --git a/Include/rangeobject.h b/Include/rangeobject.h index 145f774af8..ff6dbc2871 100644 --- a/Include/rangeobject.h +++ b/Include/rangeobject.h @@ -1,6 +1,12 @@ /* Range object interface */ +#ifndef Py_RANGEOBJECT_H +#define Py_RANGEOBJECT_H +#ifdef __cplusplus +extern "C" { +#endif + /* A range object represents an integer range. This is an immutable object; a range cannot change its value after creation. @@ -14,3 +20,8 @@ extern DL_IMPORT(PyTypeObject) PyRange_Type; #define PyRange_Check(op) ((op)->ob_type == &PyRange_Type) extern DL_IMPORT(PyObject *) PyRange_New(long, long, long, int); + +#ifdef __cplusplus +} +#endif +#endif /* !Py_RANGEOBJECT_H */ diff --git a/Include/rename1.h b/Include/rename1.h deleted file mode 100755 index 90f129f1ab..0000000000 --- a/Include/rename1.h +++ /dev/null @@ -1,360 +0,0 @@ -#ifndef Py_RENAME1_H -#define Py_RENAME1_H -#ifdef __cplusplus -extern "C" { -#endif - -/*********************************************************** -Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, -The Netherlands. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, -provided that the above copyright notice appear in all copies and that -both that copyright notice and this permission notice appear in -supporting documentation, and that the names of Stichting Mathematisch -Centrum or CWI not be used in advertising or publicity pertaining to -distribution of the software without specific, written prior permission. - -STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO -THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE -FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -******************************************************************/ - -/* This file contains a bunch of #defines that make it possible to use - "new style" names (e.g. PyObject) with the old style Python source - distribution. */ - -/* Remove some symbols (these conflict with X11 symbols) */ -#undef True -#undef False -#undef None - -typedef ANY *PyUnivPtr; -typedef struct methodlist PyMethodDef; - -#define Py_NO_DEBUG NDEBUG -#define Py_TRACE_REFS TRACE_REFS -#define Py_REF_DEBUG REF_DEBUG -#define Py_HAVE_PROTOTYPES HAVE_PROTOTYPES -#define Py_HAVE_STDLIB HAVE_STDLIB -#define _Py_ZeroStruct FalseObject -#define _Py_NoneStruct NoObject -#define _Py_TrueStruct TrueObject -#define Py_DebugFlag debugging -#define _PyParser_Grammar gram -#define _PySys_ProfileFunc sys_profile -#define _PySys_TraceFunc sys_trace -#define _PyThread_Started threads_started -#define _PyParser_TokenNames tok_name -#define Py_VerboseFlag verbose -#define PyExc_AttributeError AttributeError -#define PyExc_EOFError EOFError -#define PyExc_IOError IOError -#define PyExc_ImportError ImportError -#define PyExc_IndexError IndexError -#define PyExc_KeyError KeyError -#define PyExc_MemoryError MemoryError -#define PyExc_NameError NameError -#define PyExc_OverflowError OverflowError -#define PyExc_RuntimeError RuntimeError -#define PyExc_SyntaxError SyntaxError -#define PyExc_SystemError SystemError -#define PyExc_TypeError TypeError -#define PyExc_ValueError ValueError -#define PyExc_ZeroDivisionError ZeroDivisionError -#define PyExc_KeyboardInterrupt KeyboardInterrupt -#define PyExc_SystemExit SystemExit -#define PyFloat_Type Floattype -#define PyInt_Type Inttype -#define PyLong_Type Longtype -#define PyNothing_Type Notype -#define PyString_Type Stringtype -#define PyType_Type Typetype -#define PyList_Type Listtype -#define PyDict_Type Dicttype -#define PyTuple_Type Tupletype -#define PyFile_Type Filetype -#define PyClass_Type Classtype -#define PyFunction_Type Functype -#define PyMethod_Type Instancemethodtype -#define PyInstance_Type Instancetype -#define PyCFunction_Type Methodtype -#define PyModule_Type Moduletype -#define PyCode_Type Codetype -#define PyFrame_Type Frametype -#define PyFloatObject floatobject -#define PyIntObject intobject -#define PyLongObject longobject -#define PyNothingObject noobject -#define PyObject object -#define PyStringObject stringobject -#define PyTypeObject typeobject -#define PyListObject listobject -#define PyDictObject dictobject -#define PyTupleObject tupleobject -#define PyFileObject fileobject -#define PyClassObject classobject -#define PyCodeObject codeobject -#define PyFrameObject frameobject -#define PyFunctionObject funcobject -#define PyMethodObject instancemethodobject -#define PyInstanceObject instanceobject -#define PyCFunctionObject methodobject -#define PyModuleObject moduleobject -#define PyNumberMethods number_methods -#define PySequenceMethods sequence_methods -#define PyMappingMethods mapping_methods -#define PyObject_HEAD OB_HEAD -#define PyObject_VAR_HEAD OB_VARHEAD -#define PyObject_HEAD_INIT(x) OB_HEAD_INIT(x) -#define PyObject_NEW NEWOBJ -#define PyObject_NEW_VAR NEWVAROBJ -#define Py_PROTO PROTO -#define PyMem_NEW NEW -#define PyMem_RESIZE RESIZE -#define PyMem_DEL DEL -#define PyMem_XDEL XDEL -#define Py_BEGIN_ALLOW_THREADS BGN_SAVE -#define Py_BLOCK_THREADS RET_SAVE -#define Py_UNBLOCK_THREADS RES_SAVE -#define Py_END_ALLOW_THREADS END_SAVE -#define PyFloat_Check is_floatobject -#define PyInt_Check is_intobject -#define PyLong_Check is_longobject -#define PyNothing_Check is_noobject -#define PyString_Check is_stringobject -#define PyType_Check is_typeobject -#define PyList_Check is_listobject -#define PyDict_Check is_dictobject -#define PyTuple_Check is_tupleobject -#define PyFile_Check is_fileobject -#define PyClass_Check is_classobject -#define PyCode_Check is_codeobject -#define PyFrame_Check is_frameobject -#define PyFunction_Check is_funcobject -#define PyMethod_Check is_instancemethodobject -#define PyInstance_Check is_instanceobject -#define PyCFunction_Check is_methodobject -#define PyModule_Check is_moduleobject -#define Py_INCREF INCREF -#define Py_DECREF DECREF -#define Py_XINCREF XINCREF -#define Py_XDECREF XDECREF -#define _Py_NewReference NEWREF -#define _Py_Dealloc DELREF -#define _Py_ForgetReference UNREF -#define Py_None (&_Py_NoneStruct) -#define Py_False ((object *) &_Py_ZeroStruct) -#define Py_True ((object *) &_Py_TrueStruct) -#define PyObject_Compare cmpobject -#define PyObject_GetAttrString getattr -#define PyObject_GetAttr getattro -#define PyObject_Hash hashobject -#define _PyObject_New newobject -#define _PyObject_NewVar newvarobject -#define PyObject_Print printobject -#define PyObject_Repr reprobject -#define PyObject_SetAttrString setattr -#define PyObject_SetAttr setattro -#define PyObject_IsTrue testbool -#define Py_PRINT_RAW PRINT_RAW -#define PyFloat_AsString float_buf_repr -#define PyFloat_AsDouble getfloatvalue -#define PyFloat_AS_DOUBLE GETFLOATVALUE -#define PyFloat_FromDouble newfloatobject -#define PyInt_AsLong getintvalue -#define PyInt_AS_LONG GETINTVALUE -#define PyInt_FromLong newintobject -#define _PyLong_New alloclongobject -#define PyLong_AsDouble dgetlongvalue -#define PyLong_FromDouble dnewlongobject -#define PyLong_AsLong getlongvalue -#define PyLong_FromString long_scan -#define PyLong_FromLong newlongobject -#define PyString_Format formatstring -#define PyString_Size getstringsize -#define PyString_AsString getstringvalue -#define PyString_AS_STRING GETSTRINGVALUE -#define PyString_Concat joinstring -#define PyString_FromStringAndSize newsizedstringobject -#define PyString_FromString newstringobject -#define _PyString_Resize resizestring -#define PyList_Append addlistitem -#define PyList_GetItem getlistitem -#define PyList_GET_ITEM GETLISTITEM -#define PyList_Size getlistsize -#define PyList_GetSlice getlistslice -#define PyList_Insert inslistitem -#define PyList_New newlistobject -#define PyList_SetItem setlistitem -#define PyList_SetSlice setlistslice -#define PyList_Sort sortlist -#define PyDict_SetItemString dictinsert -#define PyDict_GetItemString dictlookup -#define PyDict_DelItemString dictremove -#define PyDict_Items getmappingitems -#define PyDict_Keys getmappingkeys -#define PyDict_Values getmappingvalues -#define PyDict_Clear mappingclear -#define PyDict_Next mappinggetnext -#define PyDict_SetItem mappinginsert -#define PyDict_GetItem mappinglookup -#define PyDict_DelItem mappingremove -#define PyDict_New newmappingobject -#define PyTuple_GetItem gettupleitem -#define PyTuple_GET_ITEM GETTUPLEITEM -#define PyTuple_Size gettuplesize -#define PyTuple_GetSlice gettupleslice -#define PyTuple_New newtupleobject -#define PyTuple_SetItem settupleitem -#define PyFile_GetLine filegetline -#define PyFile_AsFile getfilefile -#define PyFile_FromString newfileobject -#define PyFile_FromFile newopenfileobject -#define PyFile_SoftSpace softspace -#define PyFile_WriteObject writeobject -#define PyFile_WriteString writestring -#define PyMethod_Class instancemethodgetclass -#define PyMethod_Function instancemethodgetfunc -#define PyMethod_Self instancemethodgetself -#define PyClass_IsSubclass issubclass -#define PyClass_New newclassobject -#define PyMethod_New newinstancemethodobject -#define PyInstance_New newinstanceobject -#define PyTryBlock block -#define PyFrame_ExtendStack extend_stack -#define PyFrame_New newframeobject -#define PyFrame_BlockPop pop_block -#define PyFrame_BlockSetup setup_block -#define PyFunction_GetCode getfunccode -#define PyFunction_GetGlobals getfuncglobals -#define PyFunction_New newfuncobject -#define PyCFunction method -#define Py_FindMethod findmethod -#define PyCFunction_GetFunction getmethod -#define PyCFunction_GetSelf getself -#define PyCFunction_IsVarArgs getvarargs -#define PyCFunction_New newmethodobject -#define PyModule_GetDict getmoduledict -#define PyModule_GetName getmodulename -#define PyModule_New newmoduleobject -#define PyGrammar_AddAccelerators addaccelerators -#define PyGrammar_FindDFA finddfa -#define PyGrammar_LabelRepr labelrepr -#define PyNode_ListTree listtree -#define PyNode_AddChild addchild -#define PyNode_Free freetree -#define PyNode_New newtree -#define PyParser_AddToken addtoken -#define PyParser_Delete delparser -#define PyParser_New newparser -#define PyParser_ParseFile parsefile -#define PyParser_ParseString parsestring -#define PyToken_OneChar tok_1char -#define PyToken_TwoChars tok_2char -#define PyTokenizer_Free tok_free -#define PyTokenizer_Get tok_get -#define PyTokenizer_FromFile tok_setupf -#define PyTokenizer_FromString tok_setups -#define PyNode_Compile compile -#define PyCode_New newcodeobject -#define PyEval_CallObject call_object -#define PyEval_EvalCode eval_code -#define Py_FlushLine flushline -#define PyEval_GetBuiltins getbuiltins -#define PyEval_GetGlobals getglobals -#define PyEval_GetLocals getlocals -#define PyEval_InitThreads init_save_thread -#define PyErr_PrintTraceBack printtraceback -#define PyEval_RestoreThread restore_thread -#define PyEval_SaveThread save_thread -#define PyTraceBack_Fetch tb_fetch -#define PyTraceBack_Here tb_here -#define PyTraceBack_Print tb_print -#define PyTraceBack_Store tb_store -#define PyImport_AddModule add_module -#define PyImport_Cleanup doneimport -#define PyImport_GetModuleDict get_modules -#define PyImport_ImportModule import_module -#define PyImport_ImportFrozenModule init_frozen -#define PyImport_Init initimport -#define PyImport_ReloadModule reload_module -#define PyNumber_Coerce coerce -#define PyBuiltin_GetDict getbuiltindict -#define PyBuiltin_Init initbuiltin -#define PyMarshal_Init initmarshal -#define PyMarshal_ReadLongFromFile rd_long -#define PyMarshal_ReadObjectFromFile rd_object -#define PyMarshal_ReadObjectFromString rds_object -#define PyMarshal_WriteLongToFile wr_long -#define PyMarshal_WriteObjectToFile wr_object -#define PySys_Init initsys -#define PySys_SetArgv setpythonargv -#define PySys_SetPath setpythonpath -#define PySys_GetObject sysget -#define PySys_GetFile sysgetfile -#define PySys_SetObject sysset -#define Py_CompileString compile_string -#define Py_FatalError fatal -#define Py_Exit goaway -#define Py_Initialize initall -#define PyErr_Print print_error -#define PyParser_SimpleParseFile parse_file -#define PyParser_SimpleParseString parse_string -#define PyRun_AnyFile run -#define PyRun_SimpleFile run_script -#define PyRun_SimpleString run_command -#define PyRun_File run_file -#define PyRun_String run_string -#define PyRun_InteractiveOne run_tty_1 -#define PyRun_InteractiveLoop run_tty_loop -#define PyMember_Get getmember -#define PyMember_Set setmember -#define Py_InitModule(name, methods) initmodule(name, methods) -#define Py_BuildValue mkvalue -#define Py_VaBuildValue vmkvalue -#define PyArg_Parse getargs -#define PyArg_ParseTuple newgetargs -#define PyArg_NoArgs(v) getargs(v, "") -#define PyArg_GetChar getichararg -#define PyArg_GetDoubleArray getidoublearray -#define PyArg_GetFloat getifloatarg -#define PyArg_GetFloatArray getifloatarray -#define PyArg_GetInt getintarg -#define PyArg_GetLong getilongarg -#define PyArg_GetLongArray getilongarray -#define PyArg_GetLongArraySize getilongarraysize -#define PyArg_GetObject getiobjectarg -#define PyArg_GetShort getishortarg -#define PyArg_GetShortArray getishortarray -#define PyArg_GetShortArraySize getishortarraysize -#define PyArg_GetString getistringarg -#define PyErr_BadArgument err_badarg -#define PyErr_BadInternalCall err_badcall -#define PyErr_Input err_input -#define PyErr_NoMemory err_nomem -#define PyErr_SetFromErrno err_errno -#define PyErr_SetNone err_set -#define PyErr_SetString err_setstr -#define PyErr_SetObject err_setval -#define PyErr_Occurred err_occurred -#define PyErr_Fetch err_fetch -#define PyErr_Restore err_restore -#define PyErr_Clear err_clear -#define PyOS_InterruptableGetString fgets_intr -#define PyOS_InitInterrupts initintr -#define PyOS_InterruptOccurred intrcheck -#define PyOS_GetLastModificationTime getmtime - -#ifdef __cplusplus -} -#endif -#endif /* !Py_RENAME1_H */ diff --git a/LICENSE b/LICENSE index 465f691042..bb808f04c4 100644 --- a/LICENSE +++ b/LICENSE @@ -43,57 +43,47 @@ PSF LICENSE AGREEMENT 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and -otherwise using Python 2.1 software in source or binary form and its +otherwise using Python 2.1.2 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, -prepare derivative works, distribute, and otherwise use Python 2.1 +prepare derivative works, distribute, and otherwise use Python 2.1.2 alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) -2001 Python Software Foundation; All Rights Reserved" are retained in -Python 2.1 alone or in any derivative version prepared by Licensee. +2001-2002 Python Software Foundation; All Rights Reserved" are +retained in Python 2.1.2 alone or in any derivative version prepared +by Licensee. 3. In the event Licensee prepares a derivative work that is based on -or incorporates Python 2.1 or any part thereof, and wants to make +or incorporates Python 2.1.2 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of -the changes made to Python 2.1. +the changes made to Python 2.1.2. -4. PSF is making Python 2.1 available to Licensee on an "AS IS" +4. PSF is making Python 2.1.2 available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS -FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.1 WILL NOT +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 2.1.2 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON -2.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS -A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.1, +2.1.2 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.1.2, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. -7. This License Agreement shall be governed by the federal -intellectual property law of the United States, including without -limitation the federal copyright law, and, to the extent such -U.S. federal law does not apply, by the law of the Commonwealth of -Virginia, excluding Virginia's conflict of law provisions. -Notwithstanding the foregoing, with regard to derivative works based -on Python 2.1 that incorporate non-separable material that was -previously distributed under the GNU General Public License (GPL), the -law of the Commonwealth of Virginia shall govern this License -Agreement only as to issues arising under or with respect to -Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this -License Agreement shall be deemed to create any relationship of -agency, partnership, or joint venture between PSF and Licensee. This -License Agreement does not grant permission to use PSF trademarks or -trade name in a trademark sense to endorse or promote products or -services of Licensee, or any third party. +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. -8. By copying, installing or otherwise using Python 2.1, Licensee +8. By copying, installing or otherwise using Python 2.1.2, Licensee agrees to be bound by the terms and conditions of this License Agreement. diff --git a/Lib/CGIHTTPServer.py b/Lib/CGIHTTPServer.py index d6afaa105f..e724601098 100644 --- a/Lib/CGIHTTPServer.py +++ b/Lib/CGIHTTPServer.py @@ -192,6 +192,7 @@ class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): if '=' not in decoded_query: args.append(decoded_query) nobody = nobody_uid() + self.rfile.flush() # Always flush before forking self.wfile.flush() # Always flush before forking pid = os.fork() if pid != 0: @@ -221,17 +222,17 @@ class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): if self.is_python(scriptfile): interp = sys.executable if interp.lower().endswith("w.exe"): - # On Windows, use python.exe, not python.exe - interp = interp[:-5] = interp[-4:] - cmdline = "%s %s" % (interp, cmdline) + # On Windows, use python.exe, not pythonw.exe + interp = interp[:-5] + interp[-4:] + cmdline = "%s -u %s" % (interp, cmdline) if '=' not in query and '"' not in query: cmdline = '%s "%s"' % (cmdline, query) - self.log_error("command: %s", cmdline) + self.log_message("command: %s", cmdline) try: nbytes = int(length) except: nbytes = 0 - fi, fo = os.popen2(cmdline) + fi, fo = os.popen2(cmdline, 'b') if self.command.lower() == "post" and nbytes > 0: data = self.rfile.read(nbytes) fi.write(data) @@ -241,7 +242,7 @@ class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): if sts: self.log_error("CGI script exit status %#x", sts) else: - self.log_error("CGI script exited OK") + self.log_message("CGI script exited OK") else: # Other O.S. -- execute script in this process @@ -266,7 +267,7 @@ class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): except SystemExit, sts: self.log_error("CGI script exit status %s", str(sts)) else: - self.log_error("CGI script exited OK") + self.log_message("CGI script exited OK") nobody = None diff --git a/Lib/ConfigParser.py b/Lib/ConfigParser.py index cabbbdcf4f..5eae972671 100644 --- a/Lib/ConfigParser.py +++ b/Lib/ConfigParser.py @@ -431,7 +431,8 @@ class ConfigParser: if line[0] in ' \t' and cursect is not None and optname: value = line.strip() if value: - cursect[optname] = cursect[optname] + '\n ' + value + k = self.optionxform(optname) + cursect[k] = "%s\n%s" % (cursect[k], value) # a section header or option header? else: # is it a section header? diff --git a/Lib/SocketServer.py b/Lib/SocketServer.py index e5863b5adb..e52dddc3b2 100644 --- a/Lib/SocketServer.py +++ b/Lib/SocketServer.py @@ -120,7 +120,12 @@ BaseServer: # Author of the BaseServer patch: Luke Kenneth Casson Leighton -__version__ = "0.3" +# XXX Warning! +# There is a test suite for this module, but it cannot be run by the +# standard regression test. +# To run it manually, run Lib/test/test_socketserver.py. + +__version__ = "0.4" import socket @@ -129,7 +134,8 @@ import os __all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer", "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler", - "StreamRequestHandler","DatagramRequestHandler"] + "StreamRequestHandler","DatagramRequestHandler", + "ThreadingMixIn", "ForkingMixIn"] if hasattr(socket, "AF_UNIX"): __all__.extend(["UnixStreamServer","UnixDatagramServer", "ThreadingUnixStreamServer", @@ -215,7 +221,7 @@ class BaseServer: self.process_request(request, client_address) except: self.handle_error(request, client_address) - self.close_request(request) + self.close_request(request) def verify_request(self, request, client_address): """Verify the request. May be overridden. @@ -232,6 +238,7 @@ class BaseServer: """ self.finish_request(request, client_address) + self.close_request(request) def server_close(self): """Called to clean-up the server. @@ -423,18 +430,17 @@ class ForkingMixIn: if self.active_children is None: self.active_children = [] self.active_children.append(pid) + self.close_request(request) return else: # Child process. # This must never return, hence os._exit()! try: - self.server_close() self.finish_request(request, client_address) os._exit(0) except: try: - self.handle_error(request, - client_address) + self.handle_error(request, client_address) finally: os._exit(1) @@ -545,6 +551,9 @@ class StreamRequestHandler(BaseRequestHandler): class DatagramRequestHandler(BaseRequestHandler): + # XXX Regrettably, I cannot get this working on Linux; + # s.recvfrom() doesn't return a meaningful client address. + """Define self.rfile and self.wfile for datagram sockets.""" def setup(self): diff --git a/Lib/anydbm.py b/Lib/anydbm.py index ba6fa7b54a..f051200548 100644 --- a/Lib/anydbm.py +++ b/Lib/anydbm.py @@ -45,7 +45,7 @@ only if it doesn't exist; and 'n' always creates a new database. try: class error(Exception): pass -except: +except (NameError, TypeError): error = "anydbm.error" _names = ['dbhash', 'gdbm', 'dbm', 'dumbdbm'] diff --git a/Lib/asyncore.py b/Lib/asyncore.py index 145da58bdb..7340731e07 100644 --- a/Lib/asyncore.py +++ b/Lib/asyncore.py @@ -52,15 +52,8 @@ import socket import sys import os -if os.name == 'nt': - EWOULDBLOCK = 10035 - EINPROGRESS = 10036 - EALREADY = 10037 - ECONNRESET = 10054 - ENOTCONN = 10057 - ESHUTDOWN = 10058 -else: - from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, ENOTCONN, ESHUTDOWN +from errno import EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, \ + ENOTCONN, ESHUTDOWN, EINTR try: socket_map @@ -83,7 +76,11 @@ def poll (timeout=0.0, map=None): r.append (fd) if obj.writable(): w.append (fd) - r,w,e = select.select (r,w,e, timeout) + try: + r,w,e = select.select (r,w,e, timeout) + except select.error, err: + if err[0] != EINTR: + raise if DEBUG: print r,w,e @@ -161,7 +158,12 @@ def poll3 (timeout=0.0, map=None): flags = flags | select.POLLOUT if flags: pollster.register(fd, flags) - r = pollster.poll (timeout) + try: + r = pollster.poll (timeout) + except select.error, err: + if err[0] != EINTR: + raise + r = [] for fd, flags in r: try: obj = map[fd] @@ -260,7 +262,8 @@ class dispatcher: try: self.socket.setsockopt ( socket.SOL_SOCKET, socket.SO_REUSEADDR, - self.socket.getsockopt (socket.SOL_SOCKET, socket.SO_REUSEADDR) | 1 + self.socket.getsockopt (socket.SOL_SOCKET, + socket.SO_REUSEADDR) | 1 ) except: pass @@ -393,7 +396,7 @@ class dispatcher: self.handle_expt() def handle_error (self): - (file,fun,line), t, v, tbinfo = compact_traceback() + nil, t, v, tbinfo = compact_traceback() # sometimes a user repr method will crash. try: diff --git a/Lib/base64.py b/Lib/base64.py index 290fa83a04..44cd03a20f 100755 --- a/Lib/base64.py +++ b/Lib/base64.py @@ -33,19 +33,15 @@ def decode(input, output): def encodestring(s): """Encode a string.""" - import StringIO - f = StringIO.StringIO(s) - g = StringIO.StringIO() - encode(f, g) - return g.getvalue() + pieces = [] + for i in range(0, len(s), MAXBINSIZE): + chunk = s[i : i + MAXBINSIZE] + pieces.append(binascii.b2a_base64(chunk)) + return "".join(pieces) def decodestring(s): """Decode a string.""" - import StringIO - f = StringIO.StringIO(s) - g = StringIO.StringIO() - decode(f, g) - return g.getvalue() + return binascii.a2b_base64(s) def test(): """Small test program""" diff --git a/Lib/builtin.py b/Lib/builtin.py deleted file mode 100755 index 710d8253a2..0000000000 --- a/Lib/builtin.py +++ /dev/null @@ -1,3 +0,0 @@ -# B/W compat hack so code that says "import builtin" won't break after -# name change from builtin to __builtin__. -from __builtin__ import * diff --git a/Lib/cgi.py b/Lib/cgi.py index 4fa696ff1d..e03f4437c9 100755 --- a/Lib/cgi.py +++ b/Lib/cgi.py @@ -28,7 +28,7 @@ written in Python. # responsible for its maintenance. # -__version__ = "2.5" +__version__ = "2.6" # Imports @@ -243,10 +243,13 @@ def parse_multipart(fp, pdict): point in having two implementations of the same parsing algorithm. """ + boundary = "" if pdict.has_key('boundary'): boundary = pdict['boundary'] - else: - boundary = "" + if not valid_boundary(boundary): + raise ValueError, ('Invalid boundary in multipart form: %s' + % `boundary`) + nextpart = "--" + boundary lastpart = "--" + boundary + "--" partdict = {} @@ -595,14 +598,18 @@ class FieldStorage: def read_multi(self, environ, keep_blank_values, strict_parsing): """Internal: read a part that is itself multipart.""" + ib = self.innerboundary + if not valid_boundary(ib): + raise ValueError, ('Invalid boundary in multipart form: %s' + % `ib`) self.list = [] klass = self.FieldStorageClass or self.__class__ - part = klass(self.fp, {}, self.innerboundary, + part = klass(self.fp, {}, ib, environ, keep_blank_values, strict_parsing) # Throw first part away while not part.done: headers = rfc822.Message(self.fp) - part = klass(self.fp, headers, self.innerboundary, + part = klass(self.fp, headers, ib, environ, keep_blank_values, strict_parsing) self.list.append(part) self.skip_lines() @@ -633,12 +640,20 @@ class FieldStorage: def read_lines(self): """Internal: read lines until EOF or outerboundary.""" - self.file = self.make_file('') + self.file = self.__file = StringIO() if self.outerboundary: self.read_lines_to_outerboundary() else: self.read_lines_to_eof() + def __write(self, line): + if self.__file is not None: + if self.__file.tell() + len(line) > 1000: + self.file = self.make_file('') + self.file.write(self.__file.getvalue()) + self.__file = None + self.file.write(line) + def read_lines_to_eof(self): """Internal: read lines until EOF.""" while 1: @@ -646,7 +661,7 @@ class FieldStorage: if not line: self.done = -1 break - self.file.write(line) + self.__write(line) def read_lines_to_outerboundary(self): """Internal: read lines until outerboundary.""" @@ -674,7 +689,7 @@ class FieldStorage: line = line[:-1] else: delim = "" - self.file.write(odelim + line) + self.__write(odelim + line) def skip_lines(self): """Internal: skip lines until outer boundary if defined.""" @@ -991,6 +1006,9 @@ def escape(s, quote=None): s = s.replace('"', """) return s +def valid_boundary(s, _vb_pattern="^[ -~]{0,200}[!-~]$"): + import re + return re.match(_vb_pattern, s) # Invoke mainline # =============== diff --git a/Lib/compiler/pyassem.py b/Lib/compiler/pyassem.py index e8810aee00..06846233be 100644 --- a/Lib/compiler/pyassem.py +++ b/Lib/compiler/pyassem.py @@ -613,16 +613,16 @@ def twobyte(val): class LineAddrTable: """lnotab - This class builds the lnotab, which is undocumented but described - by com_set_lineno in compile.c. Here's an attempt at explanation: + This class builds the lnotab, which is documented in compile.c. + Here's a brief recap: For each SET_LINENO instruction after the first one, two bytes are added to lnotab. (In some cases, multiple two-byte entries are added.) The first byte is the distance in bytes between the instruction for the last SET_LINENO and the current SET_LINENO. The second byte is offset in line numbers. If either offset is - greater than 255, multiple two-byte entries are added -- one entry - for each factor of 255. + greater than 255, multiple two-byte entries are added -- see + compile.c for the delicate details. """ def __init__(self): @@ -657,19 +657,16 @@ class LineAddrTable: # compiler because it only generates a SET_LINENO instruction # for the assignment. if line > 0: - while addr > 0 or line > 0: - # write the values in 1-byte chunks that sum - # to desired value - trunc_addr = addr - trunc_line = line - if trunc_addr > 255: - trunc_addr = 255 - if trunc_line > 255: - trunc_line = 255 - self.lnotab.append(trunc_addr) - self.lnotab.append(trunc_line) - addr = addr - trunc_addr - line = line - trunc_line + push = self.lnotab.append + while addr > 255: + push(255); push(0) + addr -= 255 + while line > 255: + push(addr); push(255) + line -= 255 + addr = 0 + if addr > 0 or line > 0: + push(addr); push(line) self.lastline = lineno self.lastoff = self.codeOffset diff --git a/Lib/dbhash.py b/Lib/dbhash.py index ad94ed8efa..7aec772c87 100644 --- a/Lib/dbhash.py +++ b/Lib/dbhash.py @@ -12,5 +12,5 @@ __all__ = ["error","open"] error = bsddb.error # Exported for anydbm -def open(file, flag, mode=0666): +def open(file, flag = 'r', mode=0666): return bsddb.hashopen(file, flag, mode) diff --git a/Lib/distutils/__init__.py b/Lib/distutils/__init__.py index bd9761cc25..16d387a46a 100644 --- a/Lib/distutils/__init__.py +++ b/Lib/distutils/__init__.py @@ -10,4 +10,4 @@ used from a setup script as __revision__ = "$Id$" -__version__ = "1.0.2pre" +__version__ = "1.0.2" diff --git a/Lib/distutils/ccompiler.py b/Lib/distutils/ccompiler.py index 4a282d4cff..4efd93407b 100644 --- a/Lib/distutils/ccompiler.py +++ b/Lib/distutils/ccompiler.py @@ -792,8 +792,8 @@ class CCompiler: output_dir=''): if output_dir is None: output_dir = '' - if lib_type not in ("static","shared"): - raise ValueError, "'lib_type' must be \"static\" or \"shared\"" + if lib_type not in ("static","shared","dylib"): + raise ValueError, "'lib_type' must be \"static\", \"shared\" or \"dylib\"" fmt = getattr (self, lib_type + "_lib_format") ext = getattr (self, lib_type + "_lib_extension") diff --git a/Lib/distutils/command/build_scripts.py b/Lib/distutils/command/build_scripts.py index ee7f4e2d1e..28742bb746 100644 --- a/Lib/distutils/command/build_scripts.py +++ b/Lib/distutils/command/build_scripts.py @@ -9,6 +9,7 @@ __revision__ = "$Id$" import sys, os, re from distutils.core import Command from distutils.dep_util import newer +from distutils.util import convert_path # check if Python is called on the first line with this expression. # This expression will leave lines using /usr/bin/env alone; presumably @@ -56,6 +57,7 @@ class build_scripts (Command): self.mkpath(self.build_dir) for script in self.scripts: adjust = 0 + script = convert_path(script) outfile = os.path.join(self.build_dir, os.path.basename(script)) if not self.force and not newer(script, outfile): diff --git a/Lib/distutils/mwerkscompiler.py b/Lib/distutils/mwerkscompiler.py index 2edc8259bf..46e16e2e94 100644 --- a/Lib/distutils/mwerkscompiler.py +++ b/Lib/distutils/mwerkscompiler.py @@ -62,10 +62,13 @@ class MWerksCompiler (CCompiler) : debug=0, extra_preargs=None, extra_postargs=None): + (output_dir, macros, include_dirs) = \ + self._fix_compile_args (output_dir, macros, include_dirs) self.__sources = sources self.__macros = macros self.__include_dirs = include_dirs # Don't need extra_preargs and extra_postargs for CW + return [] def link (self, target_desc, @@ -80,6 +83,11 @@ class MWerksCompiler (CCompiler) : extra_preargs=None, extra_postargs=None, build_temp=None): + # First fixup. + (objects, output_dir) = self._fix_object_args (objects, output_dir) + (libraries, library_dirs, runtime_library_dirs) = \ + self._fix_lib_args (libraries, library_dirs, runtime_library_dirs) + # First examine a couple of options for things that aren't implemented yet if not target_desc in (self.SHARED_LIBRARY, self.SHARED_OBJECT): raise DistutilsPlatformError, 'Can only make SHARED_LIBRARY or SHARED_OBJECT targets on the Mac' @@ -114,6 +122,8 @@ class MWerksCompiler (CCompiler) : # into the project. if output_filename[-8:] == '.ppc.slb': basename = output_filename[:-8] + elif output_filename[-11:] == '.carbon.slb': + basename = output_filename[:-11] else: basename = os.path.strip(output_filename)[0] projectname = basename + '.mcp' @@ -162,7 +172,7 @@ class MWerksCompiler (CCompiler) : if value is None: fp.write('#define %s\n'%name) else: - fp.write('#define %s "%s"\n'%(name, value)) + fp.write('#define %s %s\n'%(name, value)) fp.close() settings['prefixname'] = prefixname @@ -198,6 +208,11 @@ class MWerksCompiler (CCompiler) : if not os.path.isabs(filename): curdir = os.getcwd() filename = os.path.join(curdir, filename) - return filename + # Finally remove .. components + components = string.split(filename, ':') + for i in range(1, len(components)): + if components[i] == '..': + components[i] = '' + return string.join(components, ':') diff --git a/Lib/distutils/sysconfig.py b/Lib/distutils/sysconfig.py index 91f9279d87..d013d1b832 100644 --- a/Lib/distutils/sysconfig.py +++ b/Lib/distutils/sysconfig.py @@ -339,7 +339,11 @@ def _init_mac(): # XXX hmmm.. a normal install puts include files here g['INCLUDEPY'] = get_python_inc(plat_specific=0) - g['SO'] = '.ppc.slb' + import MacOS + if not hasattr(MacOS, 'runtimemodel'): + g['SO'] = '.ppc.slb' + else: + g['SO'] = '.%s.slb' % MacOS.runtimemodel # XXX are these used anywhere? g['install_lib'] = os.path.join(EXEC_PREFIX, "Lib") diff --git a/Lib/distutils/unixccompiler.py b/Lib/distutils/unixccompiler.py index 9ecfb6d13b..5575bd7525 100644 --- a/Lib/distutils/unixccompiler.py +++ b/Lib/distutils/unixccompiler.py @@ -71,7 +71,8 @@ class UnixCCompiler (CCompiler): obj_extension = ".o" static_lib_extension = ".a" shared_lib_extension = ".so" - static_lib_format = shared_lib_format = "lib%s%s" + dylib_lib_extension = ".dylib" + static_lib_format = shared_lib_format = dylib_lib_format = "lib%s%s" @@ -99,12 +100,13 @@ class UnixCCompiler (CCompiler): if extra_preargs: pp_args[:0] = extra_preargs if extra_postargs: - extra_postargs.extend(extra_postargs) + pp_args.extend(extra_postargs) - # We need to preprocess: either we're being forced to, or the - # source file is newer than the target (or the target doesn't + # We need to preprocess: either we're being forced to, or we're + # generating output to stdout, or there's a target output file and + # the source file is newer than the target (or the target doesn't # exist). - if self.force or (output_file and newer(source, output_file)): + if self.force or output_file is None or newer(source, output_file): if output_file: self.mkpath(os.path.dirname(output_file)) try: @@ -258,6 +260,8 @@ class UnixCCompiler (CCompiler): for dir in dirs: shared = os.path.join( dir, self.library_filename(lib, lib_type='shared')) + dylib = os.path.join( + dir, self.library_filename(lib, lib_type='dylib')) static = os.path.join( dir, self.library_filename(lib, lib_type='static')) @@ -265,7 +269,9 @@ class UnixCCompiler (CCompiler): # data to go on: GCC seems to prefer the shared library, so I'm # assuming that *all* Unix C compilers do. And of course I'm # ignoring even GCC's "-static" option. So sue me. - if os.path.exists(shared): + if os.path.exists(dylib): + return dylib + elif os.path.exists(shared): return shared elif os.path.exists(static): return static diff --git a/Lib/doctest.py b/Lib/doctest.py index 270e3087e7..942363e762 100644 --- a/Lib/doctest.py +++ b/Lib/doctest.py @@ -450,9 +450,15 @@ class _SpoofOut: # that a trailing newline is missing. if guts and not guts.endswith("\n"): guts = guts + "\n" + # Prevent softspace from screwing up the next test case, in + # case they used print with a trailing comma in an example. + if hasattr(self, "softspace"): + del self.softspace return guts def clear(self): self.buf = [] + if hasattr(self, "softspace"): + del self.softspace def flush(self): # JPython calls flush pass @@ -500,7 +506,7 @@ def _run_examples_inner(out, fakeout, examples, globs, verbose, name): # Only compare exception type and value - the rest of # the traceback isn't necessary. want = want.split('\n')[-2] + '\n' - exc_type, exc_val, exc_tb = sys.exc_info() + exc_type, exc_val = sys.exc_info()[:2] got = traceback.format_exception_only(exc_type, exc_val)[0] state = OK else: diff --git a/Lib/dumbdbm.py b/Lib/dumbdbm.py index f1cc41bd45..f71cb8ae67 100644 --- a/Lib/dumbdbm.py +++ b/Lib/dumbdbm.py @@ -139,9 +139,14 @@ class _Database: return len(self._index) def close(self): + self._commit() self._index = None self._datfile = self._dirfile = self._bakfile = None + def __del__(self): + if self._index is not None: + self._commit() + def open(file, flag = None, mode = None): # flag, mode arguments are currently ignored diff --git a/Lib/ftplib.py b/Lib/ftplib.py index 3263281bc3..f2e90dc2c5 100644 --- a/Lib/ftplib.py +++ b/Lib/ftplib.py @@ -155,7 +155,7 @@ class FTP: def putline(self, line): line = line + CRLF if self.debugging > 1: print '*put*', self.sanitize(line) - self.sock.send(line) + self.sock.sendall(line) # Internal: send one command to the server (through putline()) def putcmd(self, line): @@ -218,7 +218,7 @@ class FTP: tried. Instead, just send the ABOR command as OOB data.''' line = 'ABOR' + CRLF if self.debugging > 1: print '*put urgent*', self.sanitize(line) - self.sock.send(line, MSG_OOB) + self.sock.sendall(line, MSG_OOB) resp = self.getmultiline() if resp[:3] not in ('426', '226'): raise error_proto, resp @@ -372,7 +372,7 @@ class FTP: while 1: buf = fp.read(blocksize) if not buf: break - conn.send(buf) + conn.sendall(buf) conn.close() return self.voidresp() @@ -386,7 +386,7 @@ class FTP: if buf[-2:] != CRLF: if buf[-1] in CRLF: buf = buf[:-1] buf = buf + CRLF - conn.send(buf) + conn.sendall(buf) conn.close() return self.voidresp() @@ -503,6 +503,8 @@ def parse150(resp): return None +_227_re = None + def parse227(resp): '''Parse the '227' response for a PASV request. Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)' @@ -510,14 +512,14 @@ def parse227(resp): if resp[:3] != '227': raise error_reply, resp - left = resp.find('(') - if left < 0: raise error_proto, resp - right = resp.find(')', left + 1) - if right < 0: - raise error_proto, resp # should contain '(h1,h2,h3,h4,p1,p2)' - numbers = resp[left+1:right].split(',') - if len(numbers) != 6: + global _227_re + if _227_re is None: + import re + _227_re = re.compile(r'(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)') + m = _227_re.search(resp) + if not m: raise error_proto, resp + numbers = m.groups() host = '.'.join(numbers[:4]) port = (int(numbers[4]) << 8) + int(numbers[5]) return host, port diff --git a/Lib/gopherlib.py b/Lib/gopherlib.py index f5bbca52b7..7d188982f7 100644 --- a/Lib/gopherlib.py +++ b/Lib/gopherlib.py @@ -66,7 +66,7 @@ def send_selector(selector, host, port = 0): port = int(port) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) - s.send(selector + CRLF) + s.sendall(selector + CRLF) s.shutdown(1) return s.makefile('rb') diff --git a/Lib/httplib.py b/Lib/httplib.py index fb87099ee9..0ca65db324 100644 --- a/Lib/httplib.py +++ b/Lib/httplib.py @@ -74,7 +74,12 @@ try: except ImportError: from StringIO import StringIO -__all__ = ["HTTP"] +__all__ = ["HTTP", "HTTPResponse", "HTTPConnection", "HTTPSConnection", + "HTTPException", "NotConnected", "UnknownProtocol", + "UnknownTransferEncoding", "IllegalKeywordArgument", + "UnimplementedFileMode", "IncompleteRead", + "ImproperConnectionState", "CannotSendRequest", "CannotSendHeader", + "ResponseNotReady", "BadStatusLine", "error"] HTTP_PORT = 80 HTTPS_PORT = 443 @@ -383,7 +388,7 @@ class HTTPConnection: if self.debuglevel > 0: print "send:", repr(str) try: - self.sock.send(str) + self.sock.sendall(str) except socket.error, v: if v[0] == 32: # Broken pipe self.close() diff --git a/Lib/idlelib/AutoExpand.py b/Lib/idlelib/AutoExpand.py deleted file mode 100644 index 0d57be4205..0000000000 --- a/Lib/idlelib/AutoExpand.py +++ /dev/null @@ -1,92 +0,0 @@ -import string -import re - -###$ event <> -###$ win -###$ unix - -class AutoExpand: - - keydefs = { - '<>': [''], - } - - unix_keydefs = { - '<>': [''], - } - - menudefs = [ - ('edit', [ - ('E_xpand word', '<>'), - ]), - ] - - wordchars = string.letters + string.digits + "_" - - def __init__(self, editwin): - self.text = editwin.text - self.text.wordlist = None # XXX what is this? - self.state = None - - def expand_word_event(self, event): - curinsert = self.text.index("insert") - curline = self.text.get("insert linestart", "insert lineend") - if not self.state: - words = self.getwords() - index = 0 - else: - words, index, insert, line = self.state - if insert != curinsert or line != curline: - words = self.getwords() - index = 0 - if not words: - self.text.bell() - return "break" - word = self.getprevword() - self.text.delete("insert - %d chars" % len(word), "insert") - newword = words[index] - index = (index + 1) % len(words) - if index == 0: - self.text.bell() # Warn we cycled around - self.text.insert("insert", newword) - curinsert = self.text.index("insert") - curline = self.text.get("insert linestart", "insert lineend") - self.state = words, index, curinsert, curline - return "break" - - def getwords(self): - word = self.getprevword() - if not word: - return [] - before = self.text.get("1.0", "insert wordstart") - wbefore = re.findall(r"\b" + word + r"\w+\b", before) - del before - after = self.text.get("insert wordend", "end") - wafter = re.findall(r"\b" + word + r"\w+\b", after) - del after - if not wbefore and not wafter: - return [] - words = [] - dict = {} - # search backwards through words before - wbefore.reverse() - for w in wbefore: - if dict.get(w): - continue - words.append(w) - dict[w] = w - # search onwards through words after - for w in wafter: - if dict.get(w): - continue - words.append(w) - dict[w] = w - words.append(word) - return words - - def getprevword(self): - line = self.text.get("insert linestart", "insert") - i = len(line) - while i > 0 and line[i-1] in self.wordchars: - i = i-1 - return line[i:] diff --git a/Lib/idlelib/AutoIndent.py b/Lib/idlelib/AutoIndent.py deleted file mode 100644 index 6d38481a42..0000000000 --- a/Lib/idlelib/AutoIndent.py +++ /dev/null @@ -1,554 +0,0 @@ -import string -#from Tkinter import TclError -#import tkMessageBox -#import tkSimpleDialog - -###$ event <> -###$ win -###$ win -###$ unix -###$ unix - -###$ event <> -###$ win -###$ unix -###$ unix - -###$ event <> -###$ win -###$ unix -###$ unix - -###$ event <> -###$ win -###$ unix - -###$ event <> -###$ win -###$ unix - -###$ event <> -###$ win -###$ unix - -###$ event <> -###$ win -###$ unix - -import PyParse - -class AutoIndent: - - menudefs = [ - ('format', [ # /s/edit/format dscherer@cmu.edu - None, - ('_Indent region', '<>'), - ('_Dedent region', '<>'), - ('Comment _out region', '<>'), - ('U_ncomment region', '<>'), - ('Tabify region', '<>'), - ('Untabify region', '<>'), - ('Toggle tabs', '<>'), - ('New indent width', '<>'), - ]), - ] - - keydefs = { - '<>': [''], - '<>': ['', ''], - '<>': [''] - } - - windows_keydefs = { - '<>': [''], - '<>': ['', # dscherer@cmu.edu - ''], - '<>': [''], - '<>': [''], - '<>': [''], - '<>': [''], - '<>': [''], - '<>': [''], - } - - unix_keydefs = { - '<>': ['', - '', - ''], - '<>': ['', - '', - ''], - '<>': ['', ''], - '<>': ['', ''], - '<>': ['', ''], - '<>': ['', ''], - '<>': [''], - '<>': [''], - } - - # usetabs true -> literal tab characters are used by indent and - # dedent cmds, possibly mixed with spaces if - # indentwidth is not a multiple of tabwidth - # false -> tab characters are converted to spaces by indent - # and dedent cmds, and ditto TAB keystrokes - # indentwidth is the number of characters per logical indent level. - # tabwidth is the display width of a literal tab character. - # CAUTION: telling Tk to use anything other than its default - # tab setting causes it to use an entirely different tabbing algorithm, - # treating tab stops as fixed distances from the left margin. - # Nobody expects this, so for now tabwidth should never be changed. - usetabs = 1 - indentwidth = 4 - tabwidth = 8 # for IDLE use, must remain 8 until Tk is fixed - - # If context_use_ps1 is true, parsing searches back for a ps1 line; - # else searches for a popular (if, def, ...) Python stmt. - context_use_ps1 = 0 - - # When searching backwards for a reliable place to begin parsing, - # first start num_context_lines[0] lines back, then - # num_context_lines[1] lines back if that didn't work, and so on. - # The last value should be huge (larger than the # of lines in a - # conceivable file). - # Making the initial values larger slows things down more often. - num_context_lines = 50, 500, 5000000 - - def __init__(self, editwin): - self.editwin = editwin - self.text = editwin.text - - def config(self, **options): - for key, value in options.items(): - if key == 'usetabs': - self.usetabs = value - elif key == 'indentwidth': - self.indentwidth = value - elif key == 'tabwidth': - self.tabwidth = value - elif key == 'context_use_ps1': - self.context_use_ps1 = value - else: - raise KeyError, "bad option name: %s" % `key` - - # If ispythonsource and guess are true, guess a good value for - # indentwidth based on file content (if possible), and if - # indentwidth != tabwidth set usetabs false. - # In any case, adjust the Text widget's view of what a tab - # character means. - - def set_indentation_params(self, ispythonsource, guess=1): - if guess and ispythonsource: - i = self.guess_indent() - if 2 <= i <= 8: - self.indentwidth = i - if self.indentwidth != self.tabwidth: - self.usetabs = 0 - - self.editwin.set_tabwidth(self.tabwidth) - - def smart_backspace_event(self, event): - text = self.text - first, last = self.editwin.get_selection_indices() - if first and last: - text.delete(first, last) - text.mark_set("insert", first) - return "break" - # Delete whitespace left, until hitting a real char or closest - # preceding virtual tab stop. - chars = text.get("insert linestart", "insert") - if chars == '': - if text.compare("insert", ">", "1.0"): - # easy: delete preceding newline - text.delete("insert-1c") - else: - text.bell() # at start of buffer - return "break" - if chars[-1] not in " \t": - # easy: delete preceding real char - text.delete("insert-1c") - return "break" - # Ick. It may require *inserting* spaces if we back up over a - # tab character! This is written to be clear, not fast. - expand, tabwidth = string.expandtabs, self.tabwidth - have = len(expand(chars, tabwidth)) - assert have > 0 - want = int((have - 1) / self.indentwidth) * self.indentwidth - ncharsdeleted = 0 - while 1: - chars = chars[:-1] - ncharsdeleted = ncharsdeleted + 1 - have = len(expand(chars, tabwidth)) - if have <= want or chars[-1] not in " \t": - break - text.undo_block_start() - text.delete("insert-%dc" % ncharsdeleted, "insert") - if have < want: - text.insert("insert", ' ' * (want - have)) - text.undo_block_stop() - return "break" - - def smart_indent_event(self, event): - # if intraline selection: - # delete it - # elif multiline selection: - # do indent-region & return - # indent one level - text = self.text - first, last = self.editwin.get_selection_indices() - text.undo_block_start() - try: - if first and last: - if index2line(first) != index2line(last): - return self.indent_region_event(event) - text.delete(first, last) - text.mark_set("insert", first) - prefix = text.get("insert linestart", "insert") - raw, effective = classifyws(prefix, self.tabwidth) - if raw == len(prefix): - # only whitespace to the left - self.reindent_to(effective + self.indentwidth) - else: - if self.usetabs: - pad = '\t' - else: - effective = len(string.expandtabs(prefix, - self.tabwidth)) - n = self.indentwidth - pad = ' ' * (n - effective % n) - text.insert("insert", pad) - text.see("insert") - return "break" - finally: - text.undo_block_stop() - - def newline_and_indent_event(self, event): - text = self.text - first, last = self.editwin.get_selection_indices() - text.undo_block_start() - try: - if first and last: - text.delete(first, last) - text.mark_set("insert", first) - line = text.get("insert linestart", "insert") - i, n = 0, len(line) - while i < n and line[i] in " \t": - i = i+1 - if i == n: - # the cursor is in or at leading indentation; just inject - # an empty line at the start - text.insert("insert linestart", '\n') - return "break" - indent = line[:i] - # strip whitespace before insert point - i = 0 - while line and line[-1] in " \t": - line = line[:-1] - i = i+1 - if i: - text.delete("insert - %d chars" % i, "insert") - # strip whitespace after insert point - while text.get("insert") in " \t": - text.delete("insert") - # start new line - text.insert("insert", '\n') - - # adjust indentation for continuations and block - # open/close first need to find the last stmt - lno = index2line(text.index('insert')) - y = PyParse.Parser(self.indentwidth, self.tabwidth) - for context in self.num_context_lines: - startat = max(lno - context, 1) - startatindex = `startat` + ".0" - rawtext = text.get(startatindex, "insert") - y.set_str(rawtext) - bod = y.find_good_parse_start( - self.context_use_ps1, - self._build_char_in_string_func(startatindex)) - if bod is not None or startat == 1: - break - y.set_lo(bod or 0) - c = y.get_continuation_type() - if c != PyParse.C_NONE: - # The current stmt hasn't ended yet. - if c == PyParse.C_STRING: - # inside a string; just mimic the current indent - text.insert("insert", indent) - elif c == PyParse.C_BRACKET: - # line up with the first (if any) element of the - # last open bracket structure; else indent one - # level beyond the indent of the line with the - # last open bracket - self.reindent_to(y.compute_bracket_indent()) - elif c == PyParse.C_BACKSLASH: - # if more than one line in this stmt already, just - # mimic the current indent; else if initial line - # has a start on an assignment stmt, indent to - # beyond leftmost =; else to beyond first chunk of - # non-whitespace on initial line - if y.get_num_lines_in_stmt() > 1: - text.insert("insert", indent) - else: - self.reindent_to(y.compute_backslash_indent()) - else: - assert 0, "bogus continuation type " + `c` - return "break" - - # This line starts a brand new stmt; indent relative to - # indentation of initial line of closest preceding - # interesting stmt. - indent = y.get_base_indent_string() - text.insert("insert", indent) - if y.is_block_opener(): - self.smart_indent_event(event) - elif indent and y.is_block_closer(): - self.smart_backspace_event(event) - return "break" - finally: - text.see("insert") - text.undo_block_stop() - - auto_indent = newline_and_indent_event - - # Our editwin provides a is_char_in_string function that works - # with a Tk text index, but PyParse only knows about offsets into - # a string. This builds a function for PyParse that accepts an - # offset. - - def _build_char_in_string_func(self, startindex): - def inner(offset, _startindex=startindex, - _icis=self.editwin.is_char_in_string): - return _icis(_startindex + "+%dc" % offset) - return inner - - def indent_region_event(self, event): - head, tail, chars, lines = self.get_region() - for pos in range(len(lines)): - line = lines[pos] - if line: - raw, effective = classifyws(line, self.tabwidth) - effective = effective + self.indentwidth - lines[pos] = self._make_blanks(effective) + line[raw:] - self.set_region(head, tail, chars, lines) - return "break" - - def dedent_region_event(self, event): - head, tail, chars, lines = self.get_region() - for pos in range(len(lines)): - line = lines[pos] - if line: - raw, effective = classifyws(line, self.tabwidth) - effective = max(effective - self.indentwidth, 0) - lines[pos] = self._make_blanks(effective) + line[raw:] - self.set_region(head, tail, chars, lines) - return "break" - - def comment_region_event(self, event): - head, tail, chars, lines = self.get_region() - for pos in range(len(lines) - 1): - line = lines[pos] - lines[pos] = '##' + line - self.set_region(head, tail, chars, lines) - - def uncomment_region_event(self, event): - head, tail, chars, lines = self.get_region() - for pos in range(len(lines)): - line = lines[pos] - if not line: - continue - if line[:2] == '##': - line = line[2:] - elif line[:1] == '#': - line = line[1:] - lines[pos] = line - self.set_region(head, tail, chars, lines) - - def tabify_region_event(self, event): - head, tail, chars, lines = self.get_region() - tabwidth = self._asktabwidth() - for pos in range(len(lines)): - line = lines[pos] - if line: - raw, effective = classifyws(line, tabwidth) - ntabs, nspaces = divmod(effective, tabwidth) - lines[pos] = '\t' * ntabs + ' ' * nspaces + line[raw:] - self.set_region(head, tail, chars, lines) - - def untabify_region_event(self, event): - head, tail, chars, lines = self.get_region() - tabwidth = self._asktabwidth() - for pos in range(len(lines)): - lines[pos] = string.expandtabs(lines[pos], tabwidth) - self.set_region(head, tail, chars, lines) - - def toggle_tabs_event(self, event): - if self.editwin.askyesno( - "Toggle tabs", - "Turn tabs " + ("on", "off")[self.usetabs] + "?", - parent=self.text): - self.usetabs = not self.usetabs - return "break" - - # XXX this isn't bound to anything -- see class tabwidth comments - def change_tabwidth_event(self, event): - new = self._asktabwidth() - if new != self.tabwidth: - self.tabwidth = new - self.set_indentation_params(0, guess=0) - return "break" - - def change_indentwidth_event(self, event): - new = self.editwin.askinteger( - "Indent width", - "New indent width (1-16)", - parent=self.text, - initialvalue=self.indentwidth, - minvalue=1, - maxvalue=16) - if new and new != self.indentwidth: - self.indentwidth = new - return "break" - - def get_region(self): - text = self.text - first, last = self.editwin.get_selection_indices() - if first and last: - head = text.index(first + " linestart") - tail = text.index(last + "-1c lineend +1c") - else: - head = text.index("insert linestart") - tail = text.index("insert lineend +1c") - chars = text.get(head, tail) - lines = string.split(chars, "\n") - return head, tail, chars, lines - - def set_region(self, head, tail, chars, lines): - text = self.text - newchars = string.join(lines, "\n") - if newchars == chars: - text.bell() - return - text.tag_remove("sel", "1.0", "end") - text.mark_set("insert", head) - text.undo_block_start() - text.delete(head, tail) - text.insert(head, newchars) - text.undo_block_stop() - text.tag_add("sel", head, "insert") - - # Make string that displays as n leading blanks. - - def _make_blanks(self, n): - if self.usetabs: - ntabs, nspaces = divmod(n, self.tabwidth) - return '\t' * ntabs + ' ' * nspaces - else: - return ' ' * n - - # Delete from beginning of line to insert point, then reinsert - # column logical (meaning use tabs if appropriate) spaces. - - def reindent_to(self, column): - text = self.text - text.undo_block_start() - if text.compare("insert linestart", "!=", "insert"): - text.delete("insert linestart", "insert") - if column: - text.insert("insert", self._make_blanks(column)) - text.undo_block_stop() - - def _asktabwidth(self): - return self.editwin.askinteger( - "Tab width", - "Spaces per tab?", - parent=self.text, - initialvalue=self.tabwidth, - minvalue=1, - maxvalue=16) or self.tabwidth - - # Guess indentwidth from text content. - # Return guessed indentwidth. This should not be believed unless - # it's in a reasonable range (e.g., it will be 0 if no indented - # blocks are found). - - def guess_indent(self): - opener, indented = IndentSearcher(self.text, self.tabwidth).run() - if opener and indented: - raw, indentsmall = classifyws(opener, self.tabwidth) - raw, indentlarge = classifyws(indented, self.tabwidth) - else: - indentsmall = indentlarge = 0 - return indentlarge - indentsmall - -# "line.col" -> line, as an int -def index2line(index): - return int(float(index)) - -# Look at the leading whitespace in s. -# Return pair (# of leading ws characters, -# effective # of leading blanks after expanding -# tabs to width tabwidth) - -def classifyws(s, tabwidth): - raw = effective = 0 - for ch in s: - if ch == ' ': - raw = raw + 1 - effective = effective + 1 - elif ch == '\t': - raw = raw + 1 - effective = (effective / tabwidth + 1) * tabwidth - else: - break - return raw, effective - -import tokenize -_tokenize = tokenize -del tokenize - -class IndentSearcher: - - # .run() chews over the Text widget, looking for a block opener - # and the stmt following it. Returns a pair, - # (line containing block opener, line containing stmt) - # Either or both may be None. - - def __init__(self, text, tabwidth): - self.text = text - self.tabwidth = tabwidth - self.i = self.finished = 0 - self.blkopenline = self.indentedline = None - - def readline(self): - if self.finished: - return "" - i = self.i = self.i + 1 - mark = `i` + ".0" - if self.text.compare(mark, ">=", "end"): - return "" - return self.text.get(mark, mark + " lineend+1c") - - def tokeneater(self, type, token, start, end, line, - INDENT=_tokenize.INDENT, - NAME=_tokenize.NAME, - OPENERS=('class', 'def', 'for', 'if', 'try', 'while')): - if self.finished: - pass - elif type == NAME and token in OPENERS: - self.blkopenline = line - elif type == INDENT and self.blkopenline: - self.indentedline = line - self.finished = 1 - - def run(self): - save_tabsize = _tokenize.tabsize - _tokenize.tabsize = self.tabwidth - try: - try: - _tokenize.tokenize(self.readline, self.tokeneater) - except _tokenize.TokenError: - # since we cut off the tokenizer early, we can trigger - # spurious errors - pass - finally: - _tokenize.tabsize = save_tabsize - return self.blkopenline, self.indentedline diff --git a/Lib/idlelib/Bindings.py b/Lib/idlelib/Bindings.py deleted file mode 100644 index 33c6c44eb0..0000000000 --- a/Lib/idlelib/Bindings.py +++ /dev/null @@ -1,67 +0,0 @@ -# This file defines the menu contents and key bindings. Note that -# there is additional configuration information in the EditorWindow -# class (and subclasses): the menus are created there based on the -# menu_specs (class) variable, and menus not created are silently -# skipped by the code here. This makes it possible to define the -# Debug menu here, which is only present in the PythonShell window. - -# changes by dscherer@cmu.edu: -# - Python shell moved to 'Run' menu -# - "Help" renamed to "IDLE Help" to distinguish from Python help. -# The distinction between the environment and the language is dim -# or nonexistent in a novice's mind. -# - Silly advice added - -import sys -import string -from keydefs import * - -menudefs = [ - # underscore prefixes character to underscore - ('file', [ - ('_New window', '<>'), - ('_Open...', '<>'), - ('Open _module...', '<>'), - ('Class _browser', '<>'), - ('_Path browser', '<>'), - None, - ('_Save', '<>'), - ('Save _As...', '<>'), - ('Save Co_py As...', '<>'), - None, - ('_Close', '<>'), - ('E_xit', '<>'), - ]), - ('edit', [ - ('_Undo', '<>'), - ('_Redo', '<>'), - None, - ('Cu_t', '<>'), - ('_Copy', '<>'), - ('_Paste', '<>'), - ('Select _All', '<>'), - ]), - ('run',[ - ('Python shell', '<>'), - ]), - ('debug', [ - ('_Go to file/line', '<>'), - ('_Stack viewer', '<>'), - ('!_Debugger', '<>'), - ('!_Auto-open stack viewer', '<>' ), - ]), - ('help', [ - ('_IDLE Help...', '<>'), - ('Python _Documentation...', '<>'), - ('_Advice...', '<>'), - None, - ('_About IDLE...', '<>'), - ]), -] - -if sys.platform == 'win32': - default_keydefs = windows_keydefs -else: - default_keydefs = unix_keydefs - -del sys diff --git a/Lib/idlelib/CallTipWindow.py b/Lib/idlelib/CallTipWindow.py deleted file mode 100644 index cbeab8cc15..0000000000 --- a/Lib/idlelib/CallTipWindow.py +++ /dev/null @@ -1,71 +0,0 @@ -# A CallTip window class for Tkinter/IDLE. -# After ToolTip.py, which uses ideas gleaned from PySol - -# Used by the CallTips IDLE extension. -import os -from Tkinter import * - -class CallTip: - - def __init__(self, widget): - self.widget = widget - self.tipwindow = None - self.id = None - self.x = self.y = 0 - - def showtip(self, text): - self.text = text - if self.tipwindow or not self.text: - return - self.widget.see("insert") - x, y, cx, cy = self.widget.bbox("insert") - x = x + self.widget.winfo_rootx() + 2 - y = y + cy + self.widget.winfo_rooty() - self.tipwindow = tw = Toplevel(self.widget) - tw.wm_overrideredirect(1) - tw.wm_geometry("+%d+%d" % (x, y)) - label = Label(tw, text=self.text, justify=LEFT, - background="#ffffe0", relief=SOLID, borderwidth=1, - font = self.widget['font']) - label.pack() - - def hidetip(self): - tw = self.tipwindow - self.tipwindow = None - if tw: - tw.destroy() - - -############################### -# -# Test Code -# -class container: # Conceptually an editor_window - def __init__(self): - root = Tk() - text = self.text = Text(root) - text.pack(side=LEFT, fill=BOTH, expand=1) - text.insert("insert", "string.split") - root.update() - self.calltip = CallTip(text) - - text.event_add("<>", "(") - text.event_add("<>", ")") - text.bind("<>", self.calltip_show) - text.bind("<>", self.calltip_hide) - - text.focus_set() - # root.mainloop() # not in idle - - def calltip_show(self, event): - self.calltip.showtip("Hello world") - - def calltip_hide(self, event): - self.calltip.hidetip() - -def main(): - # Test code - c=container() - -if __name__=='__main__': - main() diff --git a/Lib/idlelib/CallTips.py b/Lib/idlelib/CallTips.py deleted file mode 100644 index 04eccde0b4..0000000000 --- a/Lib/idlelib/CallTips.py +++ /dev/null @@ -1,190 +0,0 @@ -# CallTips.py - An IDLE extension that provides "Call Tips" - ie, a floating window that -# displays parameter information as you open parens. - -import string -import sys -import types - -class CallTips: - - menudefs = [ - ] - - keydefs = { - '<>': [''], - '<>': [''], - '<>': [''], - '<>': ['', ''], - } - - windows_keydefs = { - } - - unix_keydefs = { - } - - def __init__(self, editwin): - self.editwin = editwin - self.text = editwin.text - self.calltip = None - if hasattr(self.text, "make_calltip_window"): - self._make_calltip_window = self.text.make_calltip_window - else: - self._make_calltip_window = self._make_tk_calltip_window - - def close(self): - self._make_calltip_window = None - - # Makes a Tk based calltip window. Used by IDLE, but not Pythonwin. - # See __init__ above for how this is used. - def _make_tk_calltip_window(self): - import CallTipWindow - return CallTipWindow.CallTip(self.text) - - def _remove_calltip_window(self): - if self.calltip: - self.calltip.hidetip() - self.calltip = None - - def paren_open_event(self, event): - self._remove_calltip_window() - arg_text = get_arg_text(self.get_object_at_cursor()) - if arg_text: - self.calltip_start = self.text.index("insert") - self.calltip = self._make_calltip_window() - self.calltip.showtip(arg_text) - return "" #so the event is handled normally. - - def paren_close_event(self, event): - # Now just hides, but later we should check if other - # paren'd expressions remain open. - self._remove_calltip_window() - return "" #so the event is handled normally. - - def check_calltip_cancel_event(self, event): - if self.calltip: - # If we have moved before the start of the calltip, - # or off the calltip line, then cancel the tip. - # (Later need to be smarter about multi-line, etc) - if self.text.compare("insert", "<=", self.calltip_start) or \ - self.text.compare("insert", ">", self.calltip_start + " lineend"): - self._remove_calltip_window() - return "" #so the event is handled normally. - - def calltip_cancel_event(self, event): - self._remove_calltip_window() - return "" #so the event is handled normally. - - def get_object_at_cursor(self, - wordchars="._" + string.uppercase + string.lowercase + string.digits): - # XXX - This needs to be moved to a better place - # so the "." attribute lookup code can also use it. - text = self.text - chars = text.get("insert linestart", "insert") - i = len(chars) - while i and chars[i-1] in wordchars: - i = i-1 - word = chars[i:] - if word: - # How is this for a hack! - import sys, __main__ - namespace = sys.modules.copy() - namespace.update(__main__.__dict__) - try: - return eval(word, namespace) - except: - pass - return None # Can't find an object. - -def _find_constructor(class_ob): - # Given a class object, return a function object used for the - # constructor (ie, __init__() ) or None if we can't find one. - try: - return class_ob.__init__.im_func - except AttributeError: - for base in class_ob.__bases__: - rc = _find_constructor(base) - if rc is not None: return rc - return None - -def get_arg_text(ob): - # Get a string describing the arguments for the given object. - argText = "" - if ob is not None: - argOffset = 0 - if type(ob)==types.ClassType: - # Look for the highest __init__ in the class chain. - fob = _find_constructor(ob) - if fob is None: - fob = lambda: None - else: - argOffset = 1 - elif type(ob)==types.MethodType: - # bit of a hack for methods - turn it into a function - # but we drop the "self" param. - fob = ob.im_func - argOffset = 1 - else: - fob = ob - # Try and build one for Python defined functions - if type(fob) in [types.FunctionType, types.LambdaType]: - try: - realArgs = fob.func_code.co_varnames[argOffset:fob.func_code.co_argcount] - defaults = fob.func_defaults or [] - defaults = list(map(lambda name: "=%s" % name, defaults)) - defaults = [""] * (len(realArgs)-len(defaults)) + defaults - items = map(lambda arg, dflt: arg+dflt, realArgs, defaults) - if fob.func_code.co_flags & 0x4: - items.append("...") - if fob.func_code.co_flags & 0x8: - items.append("***") - argText = string.join(items , ", ") - argText = "(%s)" % argText - except: - pass - # See if we can use the docstring - if hasattr(ob, "__doc__") and ob.__doc__: - pos = string.find(ob.__doc__, "\n") - if pos<0 or pos>70: pos=70 - if argText: argText = argText + "\n" - argText = argText + ob.__doc__[:pos] - - return argText - -################################################# -# -# Test code -# -if __name__=='__main__': - - def t1(): "()" - def t2(a, b=None): "(a, b=None)" - def t3(a, *args): "(a, ...)" - def t4(*args): "(...)" - def t5(a, *args): "(a, ...)" - def t6(a, b=None, *args, **kw): "(a, b=None, ..., ***)" - - class TC: - "(a=None, ...)" - def __init__(self, a=None, *b): "(a=None, ...)" - def t1(self): "()" - def t2(self, a, b=None): "(a, b=None)" - def t3(self, a, *args): "(a, ...)" - def t4(self, *args): "(...)" - def t5(self, a, *args): "(a, ...)" - def t6(self, a, b=None, *args, **kw): "(a, b=None, ..., ***)" - - def test( tests ): - failed=[] - for t in tests: - expected = t.__doc__ + "\n" + t.__doc__ - if get_arg_text(t) != expected: - failed.append(t) - print "%s - expected %s, but got %s" % (t, `expected`, `get_arg_text(t)`) - print "%d of %d tests failed" % (len(failed), len(tests)) - - tc = TC() - tests = t1, t2, t3, t4, t5, t6, \ - TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6 - - test(tests) diff --git a/Lib/idlelib/ChangeLog b/Lib/idlelib/ChangeLog deleted file mode 100644 index b853a34af3..0000000000 --- a/Lib/idlelib/ChangeLog +++ /dev/null @@ -1,1017 +0,0 @@ -Tue Feb 15 18:08:19 2000 Guido van Rossum - - * NEWS.txt: Notice status bar and stack viewer. - - * EditorWindow.py: Support for Moshe's status bar. - - * MultiStatusBar.py: Status bar code -- by Moshe Zadka. - - * OldStackViewer.py: - Adding the old stack viewer implementation back, for the debugger. - - * StackViewer.py: New stack viewer, uses a tree widget. - (XXX: the debugger doesn't yet use this.) - - * WindowList.py: - Correct a typo and remove an unqualified except that was hiding the error. - - * ClassBrowser.py: Add an XXX comment about the ClassBrowser AIP. - - * ChangeLog: Updated change log. - - * NEWS.txt: News update. Probably incomplete; what else is new? - - * README.txt: - Updated for pending IDLE 0.5 release (still very rough -- just getting - it out in a more convenient format than CVS). - - * TODO.txt: Tiny addition. - -Thu Sep 9 14:16:02 1999 Guido van Rossum - - * TODO.txt: A few new TODO entries. - -Thu Aug 26 23:06:22 1999 Guido van Rossum - - * Bindings.py: Add Python Documentation entry to Help menu. - - * EditorWindow.py: - Find the help.txt file relative to __file__ or ".", not in sys.path. - (Suggested by Moshe Zadka, but implemented differently.) - - Add <> event which, on Unix, brings up Netscape pointing - to http://www.python.doc/current/ (a local copy would be nice but its - location can't be predicted). Windows solution TBD. - -Wed Aug 11 14:55:43 1999 Guido van Rossum - - * TreeWidget.py: - Moshe noticed an inconsistency in his comment, so I'm rephrasing it to - be clearer. - - * TreeWidget.py: - Patch inspired by Moshe Zadka to search for the Icons directory in the - same directory as __file__, rather than searching for it along sys.path. - This works better when idle is a package. - -Thu Jul 15 13:11:02 1999 Guido van Rossum - - * TODO.txt: New wishes. - -Sat Jul 10 13:17:35 1999 Guido van Rossum - - * IdlePrefs.py: - Make the color for stderr red (i.e. the standard warning/danger/stop - color) rather than green. Suggested by Sam Schulenburg. - -Fri Jun 25 17:26:34 1999 Guido van Rossum - - * PyShell.py: Close debugger when closing. This may break a cycle. - - * Debugger.py: Break cycle on close. - - * ClassBrowser.py: Destroy the tree when closing. - - * TreeWidget.py: Add destroy() method to recursively destroy a tree. - - * PyShell.py: Extend _close() to break cycles. - Break some other cycles too (and destroy the root when done). - - * EditorWindow.py: - Add _close() method that does the actual cleanup (close() asks the - user what they want first if there's unsaved stuff, and may cancel). - It closes more than before. - - Add unload_extensions() method to unload all extensions; called from - _close(). It calls an extension's close() method if it has one. - - * Percolator.py: Add close() method that breaks cycles. - - * WidgetRedirector.py: Add unregister() method. - Unregister everything at closing. - Don't call close() in __del__, rely on explicit call to close(). - - * IOBinding.py, FormatParagraph.py, CallTips.py: - Add close() method that breaks a cycle. - -Fri Jun 11 15:03:00 1999 Guido van Rossum - - * AutoIndent.py, EditorWindow.py, FormatParagraph.py: - Tim Peters smart.patch: - - EditorWindow.py: - - + Added get_tabwidth & set_tabwidth "virtual text" methods, that get/set the - widget's view of what a tab means. - - + Moved TK_TABWIDTH_DEFAULT here from AutoIndent. - - + Renamed Mark's get_selection_index to get_selection_indices (sorry, Mark, - but the name was plain wrong ). - - FormatParagraph.py: renamed use of get_selection_index. - - AutoIndent.py: - - + Moved TK_TABWIDTH_DEFAULT to EditorWindow. - - + Rewrote set_indentation_params to use new VTW get/set_tabwidth methods. - - + Changed smart_backspace_event to delete whitespace back to closest - preceding virtual tab stop or real character (note that this may require - inserting characters if backspacing over a tab!). - - + Nuked almost references to the selection tag, in favor of using - get_selection_indices. The sole exception is in set_region, for which no - "set_selection" abstraction has yet been agreed upon. - - + Had too much fun using the spiffy new features of the format-paragraph - cmd. - -Thu Jun 10 17:48:02 1999 Guido van Rossum - - * FormatParagraph.py: - Code by Mark Hammond to format paragraphs embedded in comments. - Read the comments (which I reformatted using the new feature :-) - for some limitations. - - * EditorWindow.py: - Added abstraction get_selection_index() (Mark Hammond). Also - reformatted some comment blocks to show off a cool feature I'm about - to check in next. - - * ClassBrowser.py: - Adapt to the new pyclbr's support of listing top-level functions. If - this functionality is not present (e.g. when used with a vintage - Python 1.5.2 installation) top-level functions are not listed. - - (Hmm... Any distribution of IDLE 0.5 should probably include a copy - of the new pyclbr.py!) - - * AutoIndent.py: - Fix off-by-one error in Tim's recent change to comment_region(): the - list of lines returned by get_region() contains an empty line at the - end representing the start of the next line, and this shouldn't be - commented out! - - * CallTips.py: - Mark Hammond writes: Here is another change that allows it to work for - class creation - tries to locate an __init__ function. Also updated - the test code to reflect your new "***" change. - - * CallTipWindow.py: - Mark Hammond writes: Tim's suggestion of copying the font for the - CallTipWindow from the text control makes sense, and actually makes - the control look better IMO. - -Wed Jun 9 20:34:57 1999 Guido van Rossum - - * CallTips.py: - Append "..." if the appropriate flag (for varargs) in co_flags is set. - Ditto "***" for kwargs. - -Tue Jun 8 13:06:07 1999 Guido van Rossum - - * ReplaceDialog.py: - Hmm... Tim didn't turn "replace all" into a single undo block. - I think I like it better if it os, so here. - - * ReplaceDialog.py: Tim Peters: made replacement atomic for undo/redo. - - * AutoIndent.py: Tim Peters: - - + Set usetabs=1. Editing pyclbr.py was driving me nuts <0.6 wink>. - usetabs=1 is the Emacs pymode default too, and thanks to indentwidth != - tabwidth magical usetabs disabling, new files are still created with tabs - turned off. The only implication is that if you open a file whose first - indent is a single tab, IDLE will now magically use tabs for that file (and - set indentwidth to 8). Note that the whole scheme doesn't work right for - PythonWin, though, since Windows users typically set tabwidth to 4; Mark - probably has to hide the IDLE algorithm from them (which he already knows). - - + Changed comment_region_event to stick "##" in front of every line. The - "holes" previously left on blank lines were visually confusing (made it - needlessly hard to figure out what to uncomment later). - -Mon Jun 7 15:38:40 1999 Guido van Rossum - - * TreeWidget.py, ObjectBrowser.py: - Remove unnecessary reference to pyclbr from test() code. - - * PyParse.py: Tim Peters: - - Smarter logic for finding a parse synch point. - - Does a half to a fifth the work in normal cases; don't notice the speedup, - but makes more breathing room for other extensions. - - Speeds terrible cases by at least a factor of 10. "Terrible" == e.g. you put - """ at the start of Tkinter.py, undo it, zoom to the bottom, and start - typing in code. Used to take about 8 seconds for ENTER to respond, now some - large fraction of a second. The new code gets indented correctly, despite - that it all remains "string colored" until the colorizer catches up (after - which, ENTER appears instantaneous again). - -Fri Jun 4 19:21:19 1999 Guido van Rossum - - * extend.py: Might as well enable CallTips by default. - If there are too many complaints I'll remove it again or fix it. - -Thu Jun 3 14:32:16 1999 Guido van Rossum - - * AutoIndent.py, EditorWindow.py, PyParse.py: - New offerings by Tim Peters; he writes: - - IDLE is now the first Python editor in the Universe not confused by my - doctest.py . - - As threatened, this defines IDLE's is_char_in_string function as a - method of EditorWindow. You just need to define one similarly in - whatever it is you pass as editwin to AutoIndent; looking at the - EditorWindow.py part of the patch should make this clear. - - * GrepDialog.py: Enclose pattern in quotes in status message. - - * CallTips.py: - Mark Hammond fixed some comments and improved the way the tip text is - constructed. - -Wed Jun 2 18:18:57 1999 Guido van Rossum - - * CallTips.py: - My fix to Mark's code: restore the universal check on . - Always cancel on or . - - * CallTips.py: - A version that Mark Hammond posted to the newsgroup. Has some newer - stuff for getting the tip. Had to fix the Key-( and Key-) events - for Unix. Will have to re-apply my patch for catching KeyRelease and - ButtonRelease events. - - * CallTipWindow.py, CallTips.py: - Call tips by Mark Hammond (plus tiny fix by me.) - - * IdleHistory.py: - Changes by Mark Hammond: (1) support optional output_sep argument to - the constructor so he can eliminate the sys.ps2 that PythonWin leaves - in the source; (2) remove duplicate history items. - - * AutoIndent.py: - Changes by Mark Hammond to allow using IDLE extensions in PythonWin as - well: make three dialog routines instance variables. - - * EditorWindow.py: - Change by Mark Hammond to allow using IDLE extensions in PythonWin as - well: make three dialog routines instance variables. - -Tue Jun 1 20:06:44 1999 Guido van Rossum - - * AutoIndent.py: Hah! A fix of my own to Tim's code! - Unix bindings for <> and <> were - missing, and somehow that meant the events were never generated, - even though they were in the menu. The new Unix bindings are now - the same as the Windows bindings (M-t and M-u). - - * AutoIndent.py, PyParse.py, PyShell.py: Tim Peters again: - - The new version (attached) is fast enough all the time in every real module - I have . You can make it slow by, e.g., creating an open list with - 5,000 90-character identifiers (+ trailing comma) each on its own line, then - adding an item to the end -- but that still consumes less than a second on - my P5-166. Response time in real code appears instantaneous. - - Fixed some bugs. - - New feature: when hitting ENTER and the cursor is beyond the line's leading - indentation, whitespace is removed on both sides of the cursor; before - whitespace was removed only on the left; e.g., assuming the cursor is - between the comma and the space: - - def something(arg1, arg2): - ^ cursor to the left of here, and hit ENTER - arg2): # new line used to end up here - arg2): # but now lines up the way you expect - - New hack: AutoIndent has grown a context_use_ps1 Boolean config option, - defaulting to 0 (false) and set to 1 (only) by PyShell. Reason: handling - the fancy stuff requires looking backward for a parsing synch point; ps1 - lines are the only sensible thing to look for in a shell window, but are a - bad thing to look for in a file window (ps1 lines show up in my module - docstrings often). PythonWin's shell should set this true too. - - Persistent problem: strings containing def/class can still screw things up - completely. No improvement. Simplest workaround is on the user's head, and - consists of inserting e.g. - - def _(): pass - - (or any other def/class) after the end of the multiline string that's - screwing them up. This is especially irksome because IDLE's syntax coloring - is *not* confused, so when this happens the colors don't match the - indentation behavior they see. - - * AutoIndent.py: Tim Peters again: - - [Tim, after adding some bracket smarts to AutoIndent.py] - > ... - > What it can't possibly do without reparsing large gobs of text is - > suggest a reasonable indent level after you've *closed* a bracket - > left open on some previous line. - > ... - - The attached can, and actually fast enough to use -- most of the time. The - code is tricky beyond belief to achieve that, but it works so far; e.g., - - return len(string.expandtabs(str[self.stmt_start : - ^ indents to caret - i], - ^ indents to caret - self.tabwidth)) + 1 - ^ indents to caret - - It's about as smart as pymode now, wrt both bracket and backslash - continuation rules. It does require reparsing large gobs of text, and if it - happens to find something that looks like a "def" or "class" or sys.ps1 - buried in a multiline string, but didn't suck up enough preceding text to - see the start of the string, it's completely hosed. I can't repair that -- - it's just too slow to reparse from the start of the file all the time. - - AutoIndent has grown a new num_context_lines tuple attribute that controls - how far to look back, and-- like other params --this could/should be made - user-overridable at startup and per-file on the fly. - - * PyParse.py: New file by Tim Peters: - - One new file in the attached, PyParse.py. The LineStudier (whatever it was - called ) class was removed from AutoIndent; PyParse subsumes its - functionality. - - * AutoIndent.py: Tim Peters keeps revising this module (more to come): - - Removed "New tabwidth" menu binding. - - Added "a tab means how many spaces?" dialog to block tabify and untabify. I - think prompting for this is good now: they're usually at-most-once-per-file - commands, and IDLE can't let them change tabwidth from the Tk default - anymore, so IDLE can no longer presume to have any idea what a tab means. - - Irony: for the purpose of keeping comments aligned via tabs, Tk's - non-default approach is much nicer than the Emacs/Notepad/Codewright/vi/etc - approach. - - * EditorWindow.py: - 1. Catch NameError on import (could be raised by case mismatch on Windows). - 2. No longer need to reset pyclbr cache and show watch cursor when calling - ClassBrowser -- the ClassBrowser takes care of pyclbr and the TreeWidget - takes care of the watch cursor. - 3. Reset the focus to the current window after error message about class - browser on buffer without filename. - - * Icons/minusnode.gif, Icons/plusnode.gif: Missed a few. - - * ClassBrowser.py, PathBrowser.py: Rewritten based on TreeWidget.py - - * ObjectBrowser.py: Object browser, based on TreeWidget.py. - - * TreeWidget.py: Tree widget done right. - - * ToolTip.py: As yet unused code for tool tips. - - * ScriptBinding.py: - Ensure sys.argv[0] is the script name on Run Script. - - * ZoomHeight.py: Move zoom height functionality to separate function. - - * Icons/folder.gif, Icons/openfolder.gif, Icons/python.gif, Icons/tk.gif: - A few icons used by ../TreeWidget.py and its callers. - - * AutoIndent.py: New version by Tim Peters improves block opening test. - -Fri May 21 04:46:17 1999 Guido van Rossum - - * Attic/History.py, PyShell.py: Rename History to IdleHistory. - Add isatty() to pseudo files. - - * StackViewer.py: Make initial stack viewer wider - - * TODO.txt: New wishes - - * AutoIndent.py, EditorWindow.py, PyShell.py: - Much improved autoindent and handling of tabs, - by Tim Peters. - -Mon May 3 15:49:52 1999 Guido van Rossum - - * AutoIndent.py, EditorWindow.py, FormatParagraph.py, UndoDelegator.py: - Tim Peters writes: - - I'm still unsure, but couldn't stand the virtual event trickery so tried a - different sin (adding undo_block_start/stop methods to the Text instance in - EditorWindow.py). Like it or not, it's efficient and works . Better - idea? - - Give the attached a whirl. Even if you hate the implementation, I think - you'll like the results. Think I caught all the "block edit" cmds, - including Format Paragraph, plus subtler ones involving smart indents and - backspacing. - - * WidgetRedirector.py: Tim Peters writes: - - [W]hile trying to dope out how redirection works, stumbled into two - possible glitches. In the first, it doesn't appear to make sense to try to - rename a command that's already been destroyed; in the second, the name - "previous" doesn't really bring to mind "ignore the previous value" . - -Fri Apr 30 19:39:25 1999 Guido van Rossum - - * __init__.py: Support for using idle as a package. - - * PathBrowser.py: - Avoid listing files more than once (e.g. foomodule.so has two hits: - once for foo + module.so, once for foomodule + .so). - -Mon Apr 26 22:20:38 1999 Guido van Rossum - - * ChangeLog, ColorDelegator.py, PyShell.py: Tim Peters strikes again: - - Ho ho ho -- that's trickier than it sounded! The colorizer is working with - "line.col" strings instead of Text marks, and the absolute coordinates of - the point of interest can change across the self.update call (voice of - baffled experience, when two quick backspaces no longer fooled it, but a - backspace followed by a quick ENTER did ). - - Anyway, the attached appears to do the trick. CPU usage goes way up when - typing quickly into a long triple-quoted string, but the latency is fine for - me (a relatively fast typist on a relatively slow machine). Most of the - changes here are left over from reducing the # of vrbl names to help me - reason about the logic better; I hope the code is a *little* easier to - -Fri Apr 23 14:01:25 1999 Guido van Rossum - - * EditorWindow.py: - Provide full arguments to __import__ so it works in packagized IDLE. - -Thu Apr 22 23:20:17 1999 Guido van Rossum - - * help.txt: - Bunch of updates necessary due to recent changes; added docs for File - menu, command line and color preferences. - - * Bindings.py: Remove obsolete 'script' menu. - - * TODO.txt: Several wishes fulfilled. - - * OutputWindow.py: - Moved classes OnDemandOutputWindow and PseudoFile here, - from ScriptBinding.py where they are no longer needed. - - * ScriptBinding.py: - Mostly rewritten. Instead of the old Run module and Debug module, - there are two new commands: - - Import module (F5) imports or reloads the module and also adds its - name to the __main__ namespace. This gets executed in the PyShell - window under control of its debug settings. - - Run script (Control-F5) is similar but executes the contents of the - file directly in the __main__ namespace. - - * PyShell.py: Nits: document use of $IDLESTARTUP; display idle version - - * idlever.py: New version to celebrate new command line - - * OutputWindow.py: Added flush(), for completeness. - - * PyShell.py: - A lot of changes to make the command line more useful. You can now do: - idle.py -e file ... -- to edit files - idle.py script arg ... -- to run a script - idle.py -c cmd arg ... -- to run a command - Other options, see also the usage message (also new!) for more details: - -d -- enable debugger - -s -- run $IDLESTARTUP or $PYTHONSTARTUP - -t title -- set Python Shell window's title - sys.argv is set accordingly, unless -e is used. - sys.path is absolutized, and all relevant paths are inserted into it. - - Other changes: - - the environment in which commands are executed is now the - __main__ module - - explicitly save sys.stdout etc., don't restore from sys.__stdout__ - - new interpreter methods execsource(), execfile(), stuffsource() - - a few small nits - - * TODO.txt: - Some more TODO items. Made up my mind about command line args, - Run/Import, __main__. - - * ColorDelegator.py: - Super-elegant patch by Tim Peters that speeds up colorization - dramatically (up to 15 times he claims). Works by reading more than - one line at a time, up to 100-line chunks (starting with one line and - then doubling up to the limit). On a typical machine (e.g. Tim's - P5-166) this doesn't reduce interactive responsiveness in a noticeable - way. - -Wed Apr 21 15:49:34 1999 Guido van Rossum - - * ColorDelegator.py: - Patch by Tim Peters to speed up colorizing of big multiline strings. - -Tue Apr 20 17:32:52 1999 Guido van Rossum - - * extend.txt: - For an event 'foo-bar', the corresponding method must be called - foo_bar_event(). Therefore, fix the references to zoom_height() in - the example. - - * IdlePrefs.py: Restored the original IDLE color scheme. - - * PyShell.py, IdlePrefs.py, ColorDelegator.py, EditorWindow.py: - Color preferences code by Loren Luke (massaged by me somewhat) - - * SearchEngine.py: - Patch by Mark Favas: it fixes the search engine behaviour where an - unsuccessful search wraps around and re-searches that part of the file - between the start of the search and the end of the file - only really - an issue for very large files, but... (also removes a redundant - m.span() call). - -Mon Apr 19 16:26:02 1999 Guido van Rossum - - * TODO.txt: A few wishes are now fulfilled. - - * AutoIndent.py: Tim Peters implements some of my wishes: - - o Makes the tab key intelligently insert spaces when appropriate - (see Help list banter twixt David Ascher and me; idea stolen from - every other editor on earth ). - - o newline_and_indent_event trims trailing whitespace on the old - line (pymode and Codewright). - - o newline_and_indent_event no longer fooled by trailing whitespace or - comment after ":" (pymode, PTUI). - - o newline_and_indent_event now reduces the new line's indentation after - return, break, continue, raise and pass stmts (pymode). - - The last two are easy to fool in the presence of strings & - continuations, but pymode requires Emacs's high-powered C parsing - functions to avoid that in finite time. - -====================================================================== - Python release 1.5.2c1, IDLE version 0.4 -====================================================================== - -Wed Apr 7 18:41:59 1999 Guido van Rossum - - * README.txt, NEWS.txt: New version. - - * idlever.py: Version bump awaiting impending new release. - (Not much has changed :-( ) - -Mon Mar 29 14:52:28 1999 Guido van Rossum - - * ScriptBinding.py, PyShell.py: - At Tim Peters' recommendation, add a dummy flush() method to - PseudoFile. - -Thu Mar 11 23:21:23 1999 Guido van Rossum - - * PathBrowser.py: Don't crash when sys.path contains an empty string. - - * Attic/Outline.py: This file was never supposed to be part of IDLE. - - * PathBrowser.py: - - Don't crash in the case where a superclass is a string instead of a - pyclbr.Class object; this can happen when the superclass is - unrecognizable (to pyclbr), e.g. when module renaming is used. - - - Show a watch cursor when calling pyclbr (since it may take a while - recursively parsing imported modules!). - -Wed Mar 10 05:18:02 1999 Guido van Rossum - - * EditorWindow.py, Bindings.py: Add PathBrowser to File module - - * PathBrowser.py: "Path browser" - 4 scrolled lists displaying: - directories on sys.path - modules in selected directory - classes in selected module - methods of selected class - - Sinlge clicking in a directory, module or class item updates the next - column with info about the selected item. Double clicking in a - module, class or method item opens the file (and selects the clicked - item if it is a class or method). - - I guess eventually I should be using a tree widget for this, but the - ones I've seen don't work well enough, so for now I use the old - Smalltalk or NeXT style multi-column hierarchical browser. - - * MultiScrolledLists.py: - New utility: multiple scrolled lists in parallel - - * ScrolledList.py: - White background. - - Display "(None)" (or text of your choosing) when empty. - - Don't set the focus. - -====================================================================== - Python release 1.5.2b2, IDLE version 0.3 -====================================================================== - -Wed Feb 17 22:47:41 1999 Guido van Rossum - - * NEWS.txt: News in 0.3. - - * README.txt, idlever.py: Bump version to 0.3. - - * EditorWindow.py: - After all, we don't need to call the callbacks ourselves! - - * WindowList.py: - When deleting, call the callbacks *after* deleting the window from our list! - - * EditorWindow.py: - Fix up the Windows menu via the new callback mechanism instead of - depending on menu post commands (which don't work when the menu is - torn off). - - * WindowList.py: - Support callbacks to patch up Windows menus everywhere. - - * ChangeLog: Oh, why not. Checking in the Emacs-generated change log. - -Tue Feb 16 22:34:17 1999 Guido van Rossum - - * ScriptBinding.py: - Only pop up the stack viewer when requested in the Debug menu. - -Mon Feb 8 22:27:49 1999 Guido van Rossum - - * WindowList.py: Don't crash if a window no longer exists. - - * TODO.txt: Restructured a bit. - -Mon Feb 1 23:06:17 1999 Guido van Rossum - - * PyShell.py: Add current dir or paths of file args to sys.path. - - * Debugger.py: Add canonic() function -- for brand new bdb.py feature. - - * StackViewer.py: Protect against accessing an empty stack. - -Fri Jan 29 20:44:45 1999 Guido van Rossum - - * ZoomHeight.py: - Use only the height to decide whether to zoom in or out. - -Thu Jan 28 22:24:30 1999 Guido van Rossum - - * EditorWindow.py, FileList.py: - Make sure the Tcl variables are shared between windows. - - * PyShell.py, EditorWindow.py, Bindings.py: - Move menu/key binding code from Bindings.py to EditorWindow.py, - with changed APIs -- it makes much more sense there. - Also add a new feature: if the first character of a menu label is - a '!', it gets a checkbox. Checkboxes are bound to Boolean Tcl variables - that can be accessed through the new getvar/setvar/getrawvar API; - the variable is named after the event to which the menu is bound. - - * Debugger.py: Add Quit button to the debugger window. - - * SearchDialog.py: - When find_again() finds exactly the current selection, it's a failure. - - * idle.py, Attic/idle: Rename idle -> idle.py - -Mon Jan 18 15:18:57 1999 Guido van Rossum - - * EditorWindow.py, WindowList.py: Only deiconify when iconic. - - * TODO.txt: Misc - -Tue Jan 12 22:14:34 1999 Guido van Rossum - - * testcode.py, Attic/test.py: - Renamed test.py to testcode.py so one can import Python's - test package from inside IDLE. (Suggested by Jack Jansen.) - - * EditorWindow.py, ColorDelegator.py: - Hack to close a window that is colorizing. - - * Separator.py: Vladimir Marangozov's patch: - The separator dances too much and seems to jump by arbitrary amounts - in arbitrary directions when I try to move it for resizing the frames. - This patch makes it more quiet. - -Mon Jan 11 14:52:40 1999 Guido van Rossum - - * TODO.txt: Some requests have been fulfilled. - - * EditorWindow.py: - Set the cursor to a watch when opening the class browser (which may - take quite a while, browsing multiple files). - - Newer, better center() -- but assumes no wrapping. - - * SearchBinding.py: - Got rid of debug print statement in goto_line_event(). - - * ScriptBinding.py: - I think I like it better if it prints the traceback even when it displays - the stack viewer. - - * Debugger.py: Bind ESC to close-window. - - * ClassBrowser.py: Use a HSeparator between the classes and the items. - Make the list of classes wider by default (40 chars). - Bind ESC to close-window. - - * Separator.py: - Separator classes (draggable divider between two panes). - -Sat Jan 9 22:01:33 1999 Guido van Rossum - - * WindowList.py: - Don't traceback when wakeup() is called when the window has been destroyed. - This can happen when a torn-of Windows menu references closed windows. - And Tim Peters claims that the Windows menu is his favorite to tear off... - - * EditorWindow.py: Allow tearing off of the Windows menu. - - * StackViewer.py: Close on ESC. - - * help.txt: Updated a bunch of things (it was mostly still 0.1!) - - * extend.py: Added ScriptBinding to standard bindings. - - * ScriptBinding.py: - This now actually works. See doc string. It can run a module (i.e. - import or reload) or debug it (same with debugger control). Output - goes to a fresh output window, only created when needed. - -====================================================================== - Python release 1.5.2b1, IDLE version 0.2 -====================================================================== - -Fri Jan 8 17:26:02 1999 Guido van Rossum - - * README.txt, NEWS.txt: What's new in this release. - - * Bindings.py, PyShell.py: - Paul Prescod's patches to allow the stack viewer to pop up when a - traceback is printed. - -Thu Jan 7 00:12:15 1999 Guido van Rossum - - * FormatParagraph.py: - Change paragraph width limit to 70 (like Emacs M-Q). - - * README.txt: - Separating TODO from README. Slight reformulation of features. No - exact release date. - - * TODO.txt: Separating TODO from README. - -Mon Jan 4 21:19:09 1999 Guido van Rossum - - * FormatParagraph.py: - Hm. There was a boundary condition error at the end of the file too. - - * SearchBinding.py: Hm. Add Unix binding for replace, too. - - * keydefs.py: Ran eventparse.py again. - - * FormatParagraph.py: Added Unix Meta-q key binding; - fix find_paragraph when at start of file. - - * AutoExpand.py: Added Meta-/ binding for Unix as alt for Alt-/. - - * SearchBinding.py: - Add unix binding for grep (otherwise the menu entry doesn't work!) - - * ZoomHeight.py: Adjusted Unix height to work with fvwm96. :=( - - * GrepDialog.py: Need to import sys! - - * help.txt, extend.txt, README.txt: Formatted some paragraphs - - * extend.py, FormatParagraph.py: - Add new extension to reformat a (text) paragraph. - - * ZoomHeight.py: Typo in Win specific height setting. - -Sun Jan 3 00:47:35 1999 Guido van Rossum - - * AutoIndent.py: Added something like Tim Peters' backspace patch. - - * ZoomHeight.py: Adapted to Unix (i.e., more hardcoded constants). - -Sat Jan 2 21:28:54 1999 Guido van Rossum - - * keydefs.py, idlever.py, idle.pyw, idle.bat, help.txt, extend.txt, extend.py, eventparse.py, ZoomHeight.py, WindowList.py, UndoDelegator.py, StackViewer.py, SearchEngine.py, SearchDialogBase.py, SearchDialog.py, ScrolledList.py, SearchBinding.py, ScriptBinding.py, ReplaceDialog.py, Attic/README, README.txt, PyShell.py, Attic/PopupMenu.py, OutputWindow.py, IOBinding.py, Attic/HelpWindow.py, History.py, GrepDialog.py, FileList.py, FrameViewer.py, EditorWindow.py, Debugger.py, Delegator.py, ColorDelegator.py, Bindings.py, ClassBrowser.py, AutoExpand.py, AutoIndent.py: - Checking in IDLE 0.2. - - Much has changed -- too much, in fact, to write down. - The big news is that there's a standard way to write IDLE extensions; - see extend.txt. Some sample extensions have been provided, and - some existing code has been converted to extensions. Probably the - biggest new user feature is a new search dialog with more options, - search and replace, and even search in files (grep). - - This is exactly as downloaded from my laptop after returning - from the holidays -- it hasn't even been tested on Unix yet. - -Fri Dec 18 15:52:54 1998 Guido van Rossum - - * FileList.py, ClassBrowser.py: - Fix the class browser to work even when the file is not on sys.path. - -Tue Dec 8 20:39:36 1998 Guido van Rossum - - * Attic/turtle.py: Moved to Python 1.5.2/Lib - -Fri Nov 27 03:19:20 1998 Guido van Rossum - - * help.txt: Typo - - * EditorWindow.py, FileList.py: Support underlining of menu labels - - * Bindings.py: - New approach, separate tables for menus (platform-independent) and key - definitions (platform-specific), and generating accelerator strings - automatically from the key definitions. - -Mon Nov 16 18:37:42 1998 Guido van Rossum - - * Attic/README: Clarify portability and main program. - - * Attic/README: Added intro for 0.1 release and append Grail notes. - -Mon Oct 26 18:49:00 1998 Guido van Rossum - - * Attic/turtle.py: root is now a global called _root - -Sat Oct 24 16:38:38 1998 Guido van Rossum - - * Attic/turtle.py: Raise the root window on reset(). - Different action on WM_DELETE_WINDOW is more likely to do the right thing, - allowing us to destroy old windows. - - * Attic/turtle.py: - Split the goto() function in two: _goto() is the internal one, - using Canvas coordinates, and goto() uses turtle coordinates - and accepts variable argument lists. - - * Attic/turtle.py: Cope with destruction of the window - - * Attic/turtle.py: Turtle graphics - - * Debugger.py: Use of Breakpoint class should be bdb.Breakpoint. - -Mon Oct 19 03:33:40 1998 Guido van Rossum - - * SearchBinding.py: - Speed up the search a bit -- don't drag a mark around... - - * PyShell.py: - Change our special entries from to . - Patch linecache.checkcache() to keep our special entries alive. - Add popup menu to all editor windows to set a breakpoint. - - * Debugger.py: - Use and pass through the 'force' flag to set_dict() where appropriate. - Default source and globals checkboxes to false. - Don't interact in user_return(). - Add primitive set_breakpoint() method. - - * ColorDelegator.py: - Raise priority of 'sel' tag so its foreground (on Windows) will take - priority over text colorization (which on Windows is almost the - same color as the selection background). - - Define a tag and color for breakpoints ("BREAK"). - - * Attic/PopupMenu.py: Disable "Open stack viewer" and "help" commands. - - * StackViewer.py: - Add optional 'force' argument (default 0) to load_dict(). - If set, redo the display even if it's the same dict. - -Fri Oct 16 21:10:12 1998 Guido van Rossum - - * StackViewer.py: Do nothing when loading the same dict as before. - - * PyShell.py: Details for debugger interface. - - * Debugger.py: - Restructured and more consistent. Save checkboxes across instantiations. - - * EditorWindow.py, Attic/README, Bindings.py: - Get rid of conflicting ^X binding. Use ^W. - - * Debugger.py, StackViewer.py: - Debugger can now show local and global variables. - - * Debugger.py: Oops - - * Debugger.py, PyShell.py: Better debugger support (show stack etc). - - * Attic/PopupMenu.py: Follow renames in StackViewer module - - * StackViewer.py: - Rename classes to StackViewer (the widget) and StackBrowser (the toplevel). - - * ScrolledList.py: Add close() method - - * EditorWindow.py: Clarify 'Open Module' dialog text - - * StackViewer.py: Restructured into a browser and a widget. - -Thu Oct 15 23:27:08 1998 Guido van Rossum - - * ClassBrowser.py, ScrolledList.py: - Generalized the scrolled list which is the base for the class and - method browser into a separate class in its own module. - - * Attic/test.py: Cosmetic change - - * Debugger.py: Don't show function name if there is none - -Wed Oct 14 03:43:05 1998 Guido van Rossum - - * Debugger.py, PyShell.py: Polish the Debugger GUI a bit. - Closing it now also does the right thing. - -Tue Oct 13 23:51:13 1998 Guido van Rossum - - * Debugger.py, PyShell.py, Bindings.py: - Ad primitive debugger interface (so far it will step and show you the - source, but it doesn't yet show the stack). - - * Attic/README: Misc - - * StackViewer.py: Whoops -- referenced self.top before it was set. - - * help.txt: Added history and completion commands. - - * help.txt: Updated - - * FileList.py: Add class browser functionality. - - * StackViewer.py: - Add a close() method and bind to WM_DELETE_WINDOW protocol - - * PyShell.py: Clear the linecache before printing a traceback - - * Bindings.py: Added class browser binding. - - * ClassBrowser.py: Much improved, much left to do. - - * PyShell.py: Make the return key do what I mean more often. - - * ClassBrowser.py: - Adding the beginnings of a Class browser. Incomplete, yet. - - * EditorWindow.py, Bindings.py: - Add new command, "Open module". You select or type a module name, - and it opens the source. - -Mon Oct 12 23:59:27 1998 Guido van Rossum - - * PyShell.py: Subsume functionality from Popup menu in Debug menu. - Other stuff so the PyShell window can be resurrected from the Windows menu. - - * FileList.py: Get rid of PopUp menu. - Create a simple Windows menu. (Imperfect when Untitled windows exist.) - Add wakeup() method: deiconify, raise, focus. - - * EditorWindow.py: Generalize menu creation. - - * Bindings.py: Add Debug and Help menu items. - - * EditorWindow.py: Added a menu bar to every window. - - * Bindings.py: Add menu configuration to the event configuration. - - * Attic/PopupMenu.py: Pass a root to the help window. - - * SearchBinding.py: - Add parent argument to 'to to line number' dialog box. - -Sat Oct 10 19:15:32 1998 Guido van Rossum - - * StackViewer.py: - Add a label at the top showing (very basic) help for the stack viewer. - Add a label at the bottom showing the exception info. - - * Attic/test.py, Attic/idle: Add Unix main script and test program. - - * idle.pyw, help.txt, WidgetRedirector.py, UndoDelegator.py, StackViewer.py, SearchBinding.py, Attic/README, PyShell.py, Attic/PopupMenu.py, Percolator.py, Outline.py, IOBinding.py, History.py, Attic/HelpWindow.py, FrameViewer.py, FileList.py, EditorWindow.py, Delegator.py, ColorDelegator.py, Bindings.py, AutoIndent.py, AutoExpand.py: - Initial checking of Tk-based Python IDE. - Features: text editor with syntax coloring and undo; - subclassed into interactive Python shell which adds history. - diff --git a/Lib/idlelib/ClassBrowser.py b/Lib/idlelib/ClassBrowser.py deleted file mode 100644 index f440164258..0000000000 --- a/Lib/idlelib/ClassBrowser.py +++ /dev/null @@ -1,224 +0,0 @@ -"""Class browser. - -XXX TO DO: - -- reparse when source changed (maybe just a button would be OK?) - (or recheck on window popup) -- add popup menu with more options (e.g. doc strings, base classes, imports) -- show function argument list? (have to do pattern matching on source) -- should the classes and methods lists also be in the module's menu bar? -- add base classes to class browser tree -""" - -import os -import sys -import string -import pyclbr - -# XXX Patch pyclbr with dummies if it's vintage Python 1.5.2: -if not hasattr(pyclbr, "readmodule_ex"): - pyclbr.readmodule_ex = pyclbr.readmodule -if not hasattr(pyclbr, "Function"): - class Function(pyclbr.Class): - pass - pyclbr.Function = Function - -import PyShell -from WindowList import ListedToplevel -from TreeWidget import TreeNode, TreeItem, ScrolledCanvas - -class ClassBrowser: - - def __init__(self, flist, name, path): - # XXX This API should change, if the file doesn't end in ".py" - # XXX the code here is bogus! - self.name = name - self.file = os.path.join(path[0], self.name + ".py") - self.init(flist) - - def close(self, event=None): - self.top.destroy() - self.node.destroy() - - def init(self, flist): - self.flist = flist - # reset pyclbr - pyclbr._modules.clear() - # create top - self.top = top = ListedToplevel(flist.root) - top.protocol("WM_DELETE_WINDOW", self.close) - top.bind("", self.close) - self.settitle() - top.focus_set() - # create scrolled canvas - sc = ScrolledCanvas(top, bg="white", highlightthickness=0, takefocus=1) - sc.frame.pack(expand=1, fill="both") - item = self.rootnode() - self.node = node = TreeNode(sc.canvas, None, item) - node.update() - node.expand() - - def settitle(self): - self.top.wm_title("Class Browser - " + self.name) - self.top.wm_iconname("Class Browser") - - def rootnode(self): - return ModuleBrowserTreeItem(self.file) - -class ModuleBrowserTreeItem(TreeItem): - - def __init__(self, file): - self.file = file - - def GetText(self): - return os.path.basename(self.file) - - def GetIconName(self): - return "python" - - def GetSubList(self): - sublist = [] - for name in self.listclasses(): - item = ClassBrowserTreeItem(name, self.classes, self.file) - sublist.append(item) - return sublist - - def OnDoubleClick(self): - if os.path.normcase(self.file[-3:]) != ".py": - return - if not os.path.exists(self.file): - return - PyShell.flist.open(self.file) - - def IsExpandable(self): - return os.path.normcase(self.file[-3:]) == ".py" - - def listclasses(self): - dir, file = os.path.split(self.file) - name, ext = os.path.splitext(file) - if os.path.normcase(ext) != ".py": - return [] - try: - dict = pyclbr.readmodule_ex(name, [dir] + sys.path) - except ImportError, msg: - return [] - items = [] - self.classes = {} - for key, cl in dict.items(): - if cl.module == name: - s = key - if cl.super: - supers = [] - for sup in cl.super: - if type(sup) is type(''): - sname = sup - else: - sname = sup.name - if sup.module != cl.module: - sname = "%s.%s" % (sup.module, sname) - supers.append(sname) - s = s + "(%s)" % string.join(supers, ", ") - items.append((cl.lineno, s)) - self.classes[s] = cl - items.sort() - list = [] - for item, s in items: - list.append(s) - return list - -class ClassBrowserTreeItem(TreeItem): - - def __init__(self, name, classes, file): - self.name = name - self.classes = classes - self.file = file - try: - self.cl = self.classes[self.name] - except (IndexError, KeyError): - self.cl = None - self.isfunction = isinstance(self.cl, pyclbr.Function) - - def GetText(self): - if self.isfunction: - return "def " + self.name + "(...)" - else: - return "class " + self.name - - def GetIconName(self): - if self.isfunction: - return "python" - else: - return "folder" - - def IsExpandable(self): - if self.cl: - return not not self.cl.methods - - def GetSubList(self): - if not self.cl: - return [] - sublist = [] - for name in self.listmethods(): - item = MethodBrowserTreeItem(name, self.cl, self.file) - sublist.append(item) - return sublist - - def OnDoubleClick(self): - if not os.path.exists(self.file): - return - edit = PyShell.flist.open(self.file) - if hasattr(self.cl, 'lineno'): - lineno = self.cl.lineno - edit.gotoline(lineno) - - def listmethods(self): - if not self.cl: - return [] - items = [] - for name, lineno in self.cl.methods.items(): - items.append((lineno, name)) - items.sort() - list = [] - for item, name in items: - list.append(name) - return list - -class MethodBrowserTreeItem(TreeItem): - - def __init__(self, name, cl, file): - self.name = name - self.cl = cl - self.file = file - - def GetText(self): - return "def " + self.name + "(...)" - - def GetIconName(self): - return "python" # XXX - - def IsExpandable(self): - return 0 - - def OnDoubleClick(self): - if not os.path.exists(self.file): - return - edit = PyShell.flist.open(self.file) - edit.gotoline(self.cl.methods[self.name]) - -def main(): - try: - file = __file__ - except NameError: - file = sys.argv[0] - if sys.argv[1:]: - file = sys.argv[1] - else: - file = sys.argv[0] - dir, file = os.path.split(file) - name = os.path.splitext(file)[0] - ClassBrowser(PyShell.flist, name, [dir]) - if sys.stdin is sys.__stdin__: - mainloop() - -if __name__ == "__main__": - main() diff --git a/Lib/idlelib/ColorDelegator.py b/Lib/idlelib/ColorDelegator.py deleted file mode 100644 index 77edfe8585..0000000000 --- a/Lib/idlelib/ColorDelegator.py +++ /dev/null @@ -1,234 +0,0 @@ -import time -import string -import re -import keyword -from Tkinter import * -from Delegator import Delegator -from IdleConf import idleconf - -#$ event <> -#$ win -#$ unix - -__debug__ = 0 - - -def any(name, list): - return "(?P<%s>" % name + string.join(list, "|") + ")" - -def make_pat(): - kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" - comment = any("COMMENT", [r"#[^\n]*"]) - sqstring = r"(\b[rR])?'[^'\\\n]*(\\.[^'\\\n]*)*'?" - dqstring = r'(\b[rR])?"[^"\\\n]*(\\.[^"\\\n]*)*"?' - sq3string = r"(\b[rR])?'''[^'\\]*((\\.|'(?!''))[^'\\]*)*(''')?" - dq3string = r'(\b[rR])?"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?' - string = any("STRING", [sq3string, dq3string, sqstring, dqstring]) - return kw + "|" + comment + "|" + string + "|" + any("SYNC", [r"\n"]) - -prog = re.compile(make_pat(), re.S) -idprog = re.compile(r"\s+(\w+)", re.S) - -class ColorDelegator(Delegator): - - def __init__(self): - Delegator.__init__(self) - self.prog = prog - self.idprog = idprog - - def setdelegate(self, delegate): - if self.delegate is not None: - self.unbind("<>") - Delegator.setdelegate(self, delegate) - if delegate is not None: - self.config_colors() - self.bind("<>", self.toggle_colorize_event) - self.notify_range("1.0", "end") - - def config_colors(self): - for tag, cnf in self.tagdefs.items(): - if cnf: - apply(self.tag_configure, (tag,), cnf) - self.tag_raise('sel') - - cconf = idleconf.getsection('Colors') - - tagdefs = { - "COMMENT": cconf.getcolor("comment"), - "KEYWORD": cconf.getcolor("keyword"), - "STRING": cconf.getcolor("string"), - "DEFINITION": cconf.getcolor("definition"), - "SYNC": cconf.getcolor("sync"), - "TODO": cconf.getcolor("todo"), - "BREAK": cconf.getcolor("break"), - # The following is used by ReplaceDialog: - "hit": cconf.getcolor("hit"), - } - - def insert(self, index, chars, tags=None): - index = self.index(index) - self.delegate.insert(index, chars, tags) - self.notify_range(index, index + "+%dc" % len(chars)) - - def delete(self, index1, index2=None): - index1 = self.index(index1) - self.delegate.delete(index1, index2) - self.notify_range(index1) - - after_id = None - allow_colorizing = 1 - colorizing = 0 - - def notify_range(self, index1, index2=None): - self.tag_add("TODO", index1, index2) - if self.after_id: - if __debug__: print "colorizing already scheduled" - return - if self.colorizing: - self.stop_colorizing = 1 - if __debug__: print "stop colorizing" - if self.allow_colorizing: - if __debug__: print "schedule colorizing" - self.after_id = self.after(1, self.recolorize) - - close_when_done = None # Window to be closed when done colorizing - - def close(self, close_when_done=None): - if self.after_id: - after_id = self.after_id - self.after_id = None - if __debug__: print "cancel scheduled recolorizer" - self.after_cancel(after_id) - self.allow_colorizing = 0 - self.stop_colorizing = 1 - if close_when_done: - if not self.colorizing: - close_when_done.destroy() - else: - self.close_when_done = close_when_done - - def toggle_colorize_event(self, event): - if self.after_id: - after_id = self.after_id - self.after_id = None - if __debug__: print "cancel scheduled recolorizer" - self.after_cancel(after_id) - if self.allow_colorizing and self.colorizing: - if __debug__: print "stop colorizing" - self.stop_colorizing = 1 - self.allow_colorizing = not self.allow_colorizing - if self.allow_colorizing and not self.colorizing: - self.after_id = self.after(1, self.recolorize) - if __debug__: - print "auto colorizing turned", self.allow_colorizing and "on" or "off" - return "break" - - def recolorize(self): - self.after_id = None - if not self.delegate: - if __debug__: print "no delegate" - return - if not self.allow_colorizing: - if __debug__: print "auto colorizing is off" - return - if self.colorizing: - if __debug__: print "already colorizing" - return - try: - self.stop_colorizing = 0 - self.colorizing = 1 - if __debug__: print "colorizing..." - t0 = time.clock() - self.recolorize_main() - t1 = time.clock() - if __debug__: print "%.3f seconds" % (t1-t0) - finally: - self.colorizing = 0 - if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"): - if __debug__: print "reschedule colorizing" - self.after_id = self.after(1, self.recolorize) - if self.close_when_done: - top = self.close_when_done - self.close_when_done = None - top.destroy() - - def recolorize_main(self): - next = "1.0" - while 1: - item = self.tag_nextrange("TODO", next) - if not item: - break - head, tail = item - self.tag_remove("SYNC", head, tail) - item = self.tag_prevrange("SYNC", head) - if item: - head = item[1] - else: - head = "1.0" - - chars = "" - next = head - lines_to_get = 1 - ok = 0 - while not ok: - mark = next - next = self.index(mark + "+%d lines linestart" % - lines_to_get) - lines_to_get = min(lines_to_get * 2, 100) - ok = "SYNC" in self.tag_names(next + "-1c") - line = self.get(mark, next) - ##print head, "get", mark, next, "->", `line` - if not line: - return - for tag in self.tagdefs.keys(): - self.tag_remove(tag, mark, next) - chars = chars + line - m = self.prog.search(chars) - while m: - for key, value in m.groupdict().items(): - if value: - a, b = m.span(key) - self.tag_add(key, - head + "+%dc" % a, - head + "+%dc" % b) - if value in ("def", "class"): - m1 = self.idprog.match(chars, b) - if m1: - a, b = m1.span(1) - self.tag_add("DEFINITION", - head + "+%dc" % a, - head + "+%dc" % b) - m = self.prog.search(chars, m.end()) - if "SYNC" in self.tag_names(next + "-1c"): - head = next - chars = "" - else: - ok = 0 - if not ok: - # We're in an inconsistent state, and the call to - # update may tell us to stop. It may also change - # the correct value for "next" (since this is a - # line.col string, not a true mark). So leave a - # crumb telling the next invocation to resume here - # in case update tells us to leave. - self.tag_add("TODO", next) - self.update() - if self.stop_colorizing: - if __debug__: print "colorizing stopped" - return - - -def main(): - from Percolator import Percolator - root = Tk() - root.wm_protocol("WM_DELETE_WINDOW", root.quit) - text = Text(background="white") - text.pack(expand=1, fill="both") - text.focus_set() - p = Percolator(text) - d = ColorDelegator() - p.insertfilter(d) - root.mainloop() - -if __name__ == "__main__": - main() diff --git a/Lib/idlelib/ConfigParser.py b/Lib/idlelib/ConfigParser.py deleted file mode 100644 index e1ce9ddc7e..0000000000 --- a/Lib/idlelib/ConfigParser.py +++ /dev/null @@ -1,382 +0,0 @@ -"""Configuration file parser. - -A setup file consists of sections, lead by a "[section]" header, -and followed by "name: value" entries, with continuations and such in -the style of RFC 822. - -The option values can contain format strings which refer to other values in -the same section, or values in a special [DEFAULT] section. - -For example: - - something: %(dir)s/whatever - -would resolve the "%(dir)s" to the value of dir. All reference -expansions are done late, on demand. - -Intrinsic defaults can be specified by passing them into the -ConfigParser constructor as a dictionary. - -class: - -ConfigParser -- responsible for for parsing a list of - configuration files, and managing the parsed database. - - methods: - - __init__(defaults=None) - create the parser and specify a dictionary of intrinsic defaults. The - keys must be strings, the values must be appropriate for %()s string - interpolation. Note that `__name__' is always an intrinsic default; - it's value is the section's name. - - sections() - return all the configuration section names, sans DEFAULT - - has_section(section) - return whether the given section exists - - options(section) - return list of configuration options for the named section - - has_option(section, option) - return whether the given section has the given option - - read(filenames) - read and parse the list of named configuration files, given by - name. A single filename is also allowed. Non-existing files - are ignored. - - readfp(fp, filename=None) - read and parse one configuration file, given as a file object. - The filename defaults to fp.name; it is only used in error - messages (if fp has no `name' attribute, the string `' is used). - - get(section, option, raw=0, vars=None) - return a string value for the named option. All % interpolations are - expanded in the return values, based on the defaults passed into the - constructor and the DEFAULT section. Additional substitutions may be - provided using the `vars' argument, which must be a dictionary whose - contents override any pre-existing defaults. - - getint(section, options) - like get(), but convert value to an integer - - getfloat(section, options) - like get(), but convert value to a float - - getboolean(section, options) - like get(), but convert value to a boolean (currently defined as 0 or - 1, only) -""" - -import sys -import string -import re - -DEFAULTSECT = "DEFAULT" - - - -# exception classes -class Error: - def __init__(self, msg=''): - self._msg = msg - def __repr__(self): - return self._msg - -class NoSectionError(Error): - def __init__(self, section): - Error.__init__(self, 'No section: %s' % section) - self.section = section - -class DuplicateSectionError(Error): - def __init__(self, section): - Error.__init__(self, "Section %s already exists" % section) - self.section = section - -class NoOptionError(Error): - def __init__(self, option, section): - Error.__init__(self, "No option `%s' in section: %s" % - (option, section)) - self.option = option - self.section = section - -class InterpolationError(Error): - def __init__(self, reference, option, section, rawval): - Error.__init__(self, - "Bad value substitution:\n" - "\tsection: [%s]\n" - "\toption : %s\n" - "\tkey : %s\n" - "\trawval : %s\n" - % (section, option, reference, rawval)) - self.reference = reference - self.option = option - self.section = section - -class MissingSectionHeaderError(Error): - def __init__(self, filename, lineno, line): - Error.__init__( - self, - 'File contains no section headers.\nfile: %s, line: %d\n%s' % - (filename, lineno, line)) - self.filename = filename - self.lineno = lineno - self.line = line - -class ParsingError(Error): - def __init__(self, filename): - Error.__init__(self, 'File contains parsing errors: %s' % filename) - self.filename = filename - self.errors = [] - - def append(self, lineno, line): - self.errors.append((lineno, line)) - self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line) - - - -class ConfigParser: - def __init__(self, defaults=None): - self.__sections = {} - if defaults is None: - self.__defaults = {} - else: - self.__defaults = defaults - - def defaults(self): - return self.__defaults - - def sections(self): - """Return a list of section names, excluding [DEFAULT]""" - # self.__sections will never have [DEFAULT] in it - return self.__sections.keys() - - def add_section(self, section): - """Create a new section in the configuration. - - Raise DuplicateSectionError if a section by the specified name - already exists. - """ - if self.__sections.has_key(section): - raise DuplicateSectionError(section) - self.__sections[section] = {} - - def has_section(self, section): - """Indicate whether the named section is present in the configuration. - - The DEFAULT section is not acknowledged. - """ - return self.__sections.has_key(section) - - def options(self, section): - """Return a list of option names for the given section name.""" - try: - opts = self.__sections[section].copy() - except KeyError: - raise NoSectionError(section) - opts.update(self.__defaults) - return opts.keys() - - def has_option(self, section, option): - """Return whether the given section has the given option.""" - try: - opts = self.__sections[section] - except KeyError: - raise NoSectionError(section) - return opts.has_key(option) - - def read(self, filenames): - """Read and parse a filename or a list of filenames. - - Files that cannot be opened are silently ignored; this is - designed so that you can specify a list of potential - configuration file locations (e.g. current directory, user's - home directory, systemwide directory), and all existing - configuration files in the list will be read. A single - filename may also be given. - """ - if type(filenames) is type(''): - filenames = [filenames] - for filename in filenames: - try: - fp = open(filename) - except IOError: - continue - self.__read(fp, filename) - fp.close() - - def readfp(self, fp, filename=None): - """Like read() but the argument must be a file-like object. - - The `fp' argument must have a `readline' method. Optional - second argument is the `filename', which if not given, is - taken from fp.name. If fp has no `name' attribute, `' is - used. - - """ - if filename is None: - try: - filename = fp.name - except AttributeError: - filename = '' - self.__read(fp, filename) - - def get(self, section, option, raw=0, vars=None): - """Get an option value for a given section. - - All % interpolations are expanded in the return values, based on the - defaults passed into the constructor, unless the optional argument - `raw' is true. Additional substitutions may be provided using the - `vars' argument, which must be a dictionary whose contents overrides - any pre-existing defaults. - - The section DEFAULT is special. - """ - try: - sectdict = self.__sections[section].copy() - except KeyError: - if section == DEFAULTSECT: - sectdict = {} - else: - raise NoSectionError(section) - d = self.__defaults.copy() - d.update(sectdict) - # Update with the entry specific variables - if vars: - d.update(vars) - option = self.optionxform(option) - try: - rawval = d[option] - except KeyError: - raise NoOptionError(option, section) - # do the string interpolation - if raw: - return rawval - - value = rawval # Make it a pretty variable name - depth = 0 - while depth < 10: # Loop through this until it's done - depth = depth + 1 - if string.find(value, "%(") >= 0: - try: - value = value % d - except KeyError, key: - raise InterpolationError(key, option, section, rawval) - else: - return value - - def __get(self, section, conv, option): - return conv(self.get(section, option)) - - def getint(self, section, option): - return self.__get(section, string.atoi, option) - - def getfloat(self, section, option): - return self.__get(section, string.atof, option) - - def getboolean(self, section, option): - v = self.get(section, option) - val = string.atoi(v) - if val not in (0, 1): - raise ValueError, 'Not a boolean: %s' % v - return val - - def optionxform(self, optionstr): - return string.lower(optionstr) - - # - # Regular expressions for parsing section headers and options. Note a - # slight semantic change from the previous version, because of the use - # of \w, _ is allowed in section header names. - SECTCRE = re.compile( - r'\[' # [ - r'(?P
[-\w_.*,(){}]+)' # a lot of stuff found by IvL - r'\]' # ] - ) - OPTCRE = re.compile( - r'(?P