Python-checkins
Threads by month
- ----- 2025 -----
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2010 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2009 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2008 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2007 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2006 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2005 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2004 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2003 -----
- December
- November
- October
- September
- August
December 2010
- 15 participants
- 768 discussions

r87587 - in python/branches/py3k/Lib/turtledemo: __main__.py about_turtledemo.txt demohelp.txt
by georg.brandl Dec. 30, 2010
by georg.brandl Dec. 30, 2010
Dec. 30, 2010
Author: georg.brandl
Date: Thu Dec 30 23:31:10 2010
New Revision: 87587
Log:
Add the missing __main__.py in the turtledemo package. It seems to have been lost during some mass rename action (r86095).
Added:
python/branches/py3k/Lib/turtledemo/__main__.py (contents, props changed)
Modified:
python/branches/py3k/Lib/turtledemo/about_turtledemo.txt
python/branches/py3k/Lib/turtledemo/demohelp.txt
Added: python/branches/py3k/Lib/turtledemo/__main__.py
==============================================================================
--- (empty file)
+++ python/branches/py3k/Lib/turtledemo/__main__.py Thu Dec 30 23:31:10 2010
@@ -0,0 +1,266 @@
+#!/usr/bin/env python3
+import sys
+import os
+
+from tkinter import *
+from idlelib.Percolator import Percolator
+from idlelib.ColorDelegator import ColorDelegator
+from idlelib.textView import view_file # TextViewer
+from imp import reload
+
+import turtle
+import time
+
+demo_dir = os.path.dirname(os.path.abspath(__file__))
+
+STARTUP = 1
+READY = 2
+RUNNING = 3
+DONE = 4
+EVENTDRIVEN = 5
+
+menufont = ("Arial", 12, NORMAL)
+btnfont = ("Arial", 12, 'bold')
+txtfont = ('Lucida Console', 8, 'normal')
+
+def getExampleEntries():
+ return [entry[:-3] for entry in os.listdir(demo_dir) if
+ entry.endswith(".py") and entry[0] != '_']
+
+def showDemoHelp():
+ view_file(demo.root, "Help on turtleDemo",
+ os.path.join(demo_dir, "demohelp.txt"))
+
+def showAboutDemo():
+ view_file(demo.root, "About turtleDemo",
+ os.path.join(demo_dir, "about_turtledemo.txt"))
+
+def showAboutTurtle():
+ view_file(demo.root, "About the new turtle module.",
+ os.path.join(demo_dir, "about_turtle.txt"))
+
+class DemoWindow(object):
+
+ def __init__(self, filename=None): #, root=None):
+ self.root = root = turtle._root = Tk()
+ root.wm_protocol("WM_DELETE_WINDOW", self._destroy)
+
+ #################
+ self.mBar = Frame(root, relief=RAISED, borderwidth=2)
+ self.mBar.pack(fill=X)
+
+ self.ExamplesBtn = self.makeLoadDemoMenu()
+ self.OptionsBtn = self.makeHelpMenu()
+ self.mBar.tk_menuBar(self.ExamplesBtn, self.OptionsBtn) #, QuitBtn)
+
+ root.title('Python turtle-graphics examples')
+ #################
+ self.left_frame = left_frame = Frame(root)
+ self.text_frame = text_frame = Frame(left_frame)
+ self.vbar = vbar =Scrollbar(text_frame, name='vbar')
+ self.text = text = Text(text_frame,
+ name='text', padx=5, wrap='none',
+ width=45)
+ vbar['command'] = text.yview
+ vbar.pack(side=LEFT, fill=Y)
+ #####################
+ self.hbar = hbar =Scrollbar(text_frame, name='hbar', orient=HORIZONTAL)
+ hbar['command'] = text.xview
+ hbar.pack(side=BOTTOM, fill=X)
+ #####################
+ text['yscrollcommand'] = vbar.set
+ text.config(font=txtfont)
+ text.config(xscrollcommand=hbar.set)
+ text.pack(side=LEFT, fill=Y, expand=1)
+ #####################
+ self.output_lbl = Label(left_frame, height= 1,text=" --- ", bg = "#ddf",
+ font = ("Arial", 16, 'normal'))
+ self.output_lbl.pack(side=BOTTOM, expand=0, fill=X)
+ #####################
+ text_frame.pack(side=LEFT, fill=BOTH, expand=0)
+ left_frame.pack(side=LEFT, fill=BOTH, expand=0)
+ self.graph_frame = g_frame = Frame(root)
+
+ turtle._Screen._root = g_frame
+ turtle._Screen._canvas = turtle.ScrolledCanvas(g_frame, 800, 600, 1000, 800)
+ #xturtle.Screen._canvas.pack(expand=1, fill="both")
+ self.screen = _s_ = turtle.Screen()
+#####
+ turtle.TurtleScreen.__init__(_s_, _s_._canvas)
+#####
+ self.scanvas = _s_._canvas
+ #xturtle.RawTurtle.canvases = [self.scanvas]
+ turtle.RawTurtle.screens = [_s_]
+
+ self.scanvas.pack(side=TOP, fill=BOTH, expand=1)
+
+ self.btn_frame = btn_frame = Frame(g_frame, height=100)
+ self.start_btn = Button(btn_frame, text=" START ", font=btnfont, fg = "white",
+ disabledforeground = "#fed", command=self.startDemo)
+ self.start_btn.pack(side=LEFT, fill=X, expand=1)
+ self.stop_btn = Button(btn_frame, text=" STOP ", font=btnfont, fg = "white",
+ disabledforeground = "#fed", command = self.stopIt)
+ self.stop_btn.pack(side=LEFT, fill=X, expand=1)
+ self.clear_btn = Button(btn_frame, text=" CLEAR ", font=btnfont, fg = "white",
+ disabledforeground = "#fed", command = self.clearCanvas)
+ self.clear_btn.pack(side=LEFT, fill=X, expand=1)
+
+ self.btn_frame.pack(side=TOP, fill=BOTH, expand=0)
+ self.graph_frame.pack(side=TOP, fill=BOTH, expand=1)
+
+ Percolator(text).insertfilter(ColorDelegator())
+ self.dirty = False
+ self.exitflag = False
+ if filename:
+ self.loadfile(filename)
+ self.configGUI(NORMAL, DISABLED, DISABLED, DISABLED,
+ "Choose example from menu", "black")
+ self.state = STARTUP
+
+ def _destroy(self):
+ self.root.destroy()
+ sys.exit()
+
+ def configGUI(self, menu, start, stop, clear, txt="", color="blue"):
+ self.ExamplesBtn.config(state=menu)
+
+ self.start_btn.config(state=start)
+ if start == NORMAL:
+ self.start_btn.config(bg="#d00")
+ else:
+ self.start_btn.config(bg="#fca")
+
+ self.stop_btn.config(state=stop)
+ if stop == NORMAL:
+ self.stop_btn.config(bg="#d00")
+ else:
+ self.stop_btn.config(bg="#fca")
+ self.clear_btn.config(state=clear)
+
+ self.clear_btn.config(state=clear)
+ if clear == NORMAL:
+ self.clear_btn.config(bg="#d00")
+ else:
+ self.clear_btn.config(bg="#fca")
+
+ self.output_lbl.config(text=txt, fg=color)
+
+
+ def makeLoadDemoMenu(self):
+ CmdBtn = Menubutton(self.mBar, text='Examples', underline=0, font=menufont)
+ CmdBtn.pack(side=LEFT, padx="2m")
+ CmdBtn.menu = Menu(CmdBtn)
+
+ for entry in getExampleEntries():
+ def loadexample(x):
+ def emit():
+ self.loadfile(x)
+ return emit
+ CmdBtn.menu.add_command(label=entry, underline=0,
+ font=menufont, command=loadexample(entry))
+
+ CmdBtn['menu'] = CmdBtn.menu
+ return CmdBtn
+
+ def makeHelpMenu(self):
+ CmdBtn = Menubutton(self.mBar, text='Help', underline=0, font=menufont)
+ CmdBtn.pack(side=LEFT, padx='2m')
+ CmdBtn.menu = Menu(CmdBtn)
+
+ CmdBtn.menu.add_command(label='About turtle.py', font=menufont,
+ command=showAboutTurtle)
+ CmdBtn.menu.add_command(label='turtleDemo - Help', font=menufont,
+ command=showDemoHelp)
+ CmdBtn.menu.add_command(label='About turtleDemo', font=menufont,
+ command=showAboutDemo)
+
+ CmdBtn['menu'] = CmdBtn.menu
+ return CmdBtn
+
+ def refreshCanvas(self):
+ if not self.dirty: return
+ self.screen.clear()
+ #self.screen.mode("standard")
+ self.dirty=False
+
+ def loadfile(self, filename):
+ self.refreshCanvas()
+ modname = 'turtledemo.' + filename
+ __import__(modname)
+ self.module = sys.modules[modname]
+ with open(self.module.__file__, 'r') as f:
+ chars = f.read()
+ self.text.delete("1.0", "end")
+ self.text.insert("1.0", chars)
+ self.root.title(filename + " - a Python turtle graphics example")
+ reload(self.module)
+ self.configGUI(NORMAL, NORMAL, DISABLED, DISABLED,
+ "Press start button", "red")
+ self.state = READY
+
+ def startDemo(self):
+ self.refreshCanvas()
+ self.dirty = True
+ turtle.TurtleScreen._RUNNING = True
+ self.configGUI(DISABLED, DISABLED, NORMAL, DISABLED,
+ "demo running...", "black")
+ self.screen.clear()
+ self.screen.mode("standard")
+ self.state = RUNNING
+
+ try:
+ result = self.module.main()
+ if result == "EVENTLOOP":
+ self.state = EVENTDRIVEN
+ else:
+ self.state = DONE
+ except turtle.Terminator:
+ self.state = DONE
+ result = "stopped!"
+ if self.state == DONE:
+ self.configGUI(NORMAL, NORMAL, DISABLED, NORMAL,
+ result)
+ elif self.state == EVENTDRIVEN:
+ self.exitflag = True
+ self.configGUI(DISABLED, DISABLED, NORMAL, DISABLED,
+ "use mouse/keys or STOP", "red")
+
+ def clearCanvas(self):
+ self.refreshCanvas()
+ self.screen._delete("all")
+ self.scanvas.config(cursor="")
+ self.configGUI(NORMAL, NORMAL, DISABLED, DISABLED)
+
+ def stopIt(self):
+ if self.exitflag:
+ self.clearCanvas()
+ self.exitflag = False
+ self.configGUI(NORMAL, NORMAL, DISABLED, DISABLED,
+ "STOPPED!", "red")
+ turtle.TurtleScreen._RUNNING = False
+ #print "stopIT: exitflag = True"
+ else:
+ turtle.TurtleScreen._RUNNING = False
+ #print "stopIt: exitflag = False"
+
+if __name__ == '__main__':
+ demo = DemoWindow()
+ RUN = True
+ while RUN:
+ try:
+ #print("ENTERING mainloop")
+ demo.root.mainloop()
+ except AttributeError:
+ #print("AttributeError!- WAIT A MOMENT!")
+ time.sleep(0.3)
+ print("GOING ON ..")
+ demo.ckearCanvas()
+ except TypeError:
+ demo.screen._delete("all")
+ #print("CRASH!!!- WAIT A MOMENT!")
+ time.sleep(0.3)
+ #print("GOING ON ..")
+ demo.clearCanvas()
+ except:
+ print("BYE!")
+ RUN = False
Modified: python/branches/py3k/Lib/turtledemo/about_turtledemo.txt
==============================================================================
--- python/branches/py3k/Lib/turtledemo/about_turtledemo.txt (original)
+++ python/branches/py3k/Lib/turtledemo/about_turtledemo.txt Thu Dec 30 23:31:10 2010
@@ -1,9 +1,9 @@
--------------------------------------
- About turtleDemo.py
+ About this viewer
--------------------------------------
- Tiny demo Viewer to view turtle graphics example scripts.
+ Tiny demo viewer to view turtle graphics example scripts.
Quickly and dirtyly assembled by Gregor Lingl.
June, 2006
Modified: python/branches/py3k/Lib/turtledemo/demohelp.txt
==============================================================================
--- python/branches/py3k/Lib/turtledemo/demohelp.txt (original)
+++ python/branches/py3k/Lib/turtledemo/demohelp.txt Thu Dec 30 23:31:10 2010
@@ -53,12 +53,7 @@
(2) How to add your own demos to the demo repository
- - scriptname: must begin with tdemo_ ,
- so it must have the form tdemo_<your-script-name>.py
-
- - place: same directory as turtleDemo.py or some
- subdirectory, the name of which must also begin with
- tdemo_.....
+ - place: same directory as turtledemo/__main__.py
- requirements on source code:
code must contain a main() function which will
1
0

r87586 - in python/branches/py3k: Doc/extending/embedding.rst Doc/library/curses.rst Doc/library/imp.rst Doc/library/tkinter.rst Doc/library/tkinter.tix.rst Doc/library/turtle.rst Mac/Makefile.in Mac/README Makefile.pre.in Misc/NEWS
by georg.brandl Dec. 30, 2010
by georg.brandl Dec. 30, 2010
Dec. 30, 2010
Author: georg.brandl
Date: Thu Dec 30 23:12:40 2010
New Revision: 87586
Log:
Remove mentions of the Demo directory.
Modified:
python/branches/py3k/Doc/extending/embedding.rst
python/branches/py3k/Doc/library/curses.rst
python/branches/py3k/Doc/library/imp.rst
python/branches/py3k/Doc/library/tkinter.rst
python/branches/py3k/Doc/library/tkinter.tix.rst
python/branches/py3k/Doc/library/turtle.rst
python/branches/py3k/Mac/Makefile.in
python/branches/py3k/Mac/README
python/branches/py3k/Makefile.pre.in
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Doc/extending/embedding.rst
==============================================================================
--- python/branches/py3k/Doc/extending/embedding.rst (original)
+++ python/branches/py3k/Doc/extending/embedding.rst Thu Dec 30 23:12:40 2010
@@ -35,9 +35,6 @@
to :c:func:`PyRun_SimpleFile`. You can also call the lower-level operations
described in the previous chapters to construct and use Python objects.
-A simple demo of embedding Python can be found in the directory
-:file:`Demo/embed/` of the source distribution.
-
.. seealso::
Modified: python/branches/py3k/Doc/library/curses.rst
==============================================================================
--- python/branches/py3k/Doc/library/curses.rst (original)
+++ python/branches/py3k/Doc/library/curses.rst Thu Dec 30 23:12:40 2010
@@ -49,7 +49,7 @@
Tutorial material on using curses with Python, by Andrew Kuchling and Eric
Raymond.
- The :file:`Demo/curses/` directory in the Python source distribution contains
+ The :file:`Tools/demo/` directory in the Python source distribution contains
some example programs using the curses bindings provided by this module.
Modified: python/branches/py3k/Doc/library/imp.rst
==============================================================================
--- python/branches/py3k/Doc/library/imp.rst (original)
+++ python/branches/py3k/Doc/library/imp.rst Thu Dec 30 23:12:40 2010
@@ -308,10 +308,3 @@
# Since we may exit via an exception, close fp explicitly.
if fp:
fp.close()
-
-.. index:: module: knee
-
-A more complete example that implements hierarchical module names and includes a
-:func:`reload` function can be found in the module :mod:`knee`. The :mod:`knee`
-module can be found in :file:`Demo/imputil/` in the Python source distribution.
-
Modified: python/branches/py3k/Doc/library/tkinter.rst
==============================================================================
--- python/branches/py3k/Doc/library/tkinter.rst (original)
+++ python/branches/py3k/Doc/library/tkinter.rst Thu Dec 30 23:12:40 2010
@@ -659,9 +659,7 @@
scrollcommand
This is almost always the :meth:`!set` method of some scrollbar widget, but can
- be any widget method that takes a single argument. Refer to the file
- :file:`Demo/tkinter/matt/canvas-with-scrollbars.py` in the Python source
- distribution for an example.
+ be any widget method that takes a single argument.
wrap:
Must be one of: ``"none"``, ``"char"``, or ``"word"``.
Modified: python/branches/py3k/Doc/library/tkinter.tix.rst
==============================================================================
--- python/branches/py3k/Doc/library/tkinter.tix.rst (original)
+++ python/branches/py3k/Doc/library/tkinter.tix.rst Thu Dec 30 23:12:40 2010
@@ -84,11 +84,7 @@
-----------
`Tix <http://tix.sourceforge.net/dist/current/man/html/TixCmd/TixIntro.htm>`_
-introduces over 40 widget classes to the :mod:`tkinter` repertoire. There is a
-demo of all the :mod:`tkinter.tix` widgets in the :file:`Demo/tix` directory of
-the standard distribution.
-
-.. The Python sample code is still being added to Python, hence commented out
+introduces over 40 widget classes to the :mod:`tkinter` repertoire.
Basic Widgets
Modified: python/branches/py3k/Doc/library/turtle.rst
==============================================================================
--- python/branches/py3k/Doc/library/turtle.rst (original)
+++ python/branches/py3k/Doc/library/turtle.rst Thu Dec 30 23:12:40 2010
@@ -2268,7 +2268,7 @@
stored and an additional one in the current working directory. The latter will
override the settings of the first one.
-The :file:`Demo/turtle` directory contains a :file:`turtle.cfg` file. You can
+The :file:`Lib/turtledemo` directory contains a :file:`turtle.cfg` file. You can
study it as an example and see its effects when running the demos (preferably
not from within the demo-viewer).
@@ -2400,8 +2400,7 @@
strings and numbers respectively.
- Two example scripts :file:`tdemo_nim.py` and :file:`tdemo_round_dance.py`
- have been added to the Demo directory (source distribution only). As usual
- they can be viewed and executed within the demo viewer :file:`turtleDemo.py`.
+ have been added to the :file:`Lib/turtledemo` directory.
.. doctest::
Modified: python/branches/py3k/Mac/Makefile.in
==============================================================================
--- python/branches/py3k/Mac/Makefile.in (original)
+++ python/branches/py3k/Mac/Makefile.in Thu Dec 30 23:12:40 2010
@@ -202,10 +202,6 @@
installextras: $(srcdir)/Extras.ReadMe.txt $(srcdir)/Extras.install.py
$(INSTALL) -d "$(DESTDIR)$(PYTHONAPPSDIR)/Extras"
$(INSTALL) $(srcdir)/Extras.ReadMe.txt "$(DESTDIR)$(PYTHONAPPSDIR)/Extras/ReadMe.txt"
- $(RUNSHARED) $(BUILDPYTHON) $(srcdir)/Extras.install.py $(srcdir)/../Demo \
- "$(DESTDIR)$(PYTHONAPPSDIR)/Extras/Demo"
- $(RUNSHARED) $(BUILDPYTHON) $(srcdir)/Extras.install.py $(srcdir)/Demo \
- "$(DESTDIR)$(PYTHONAPPSDIR)/Extras/Demo.Mac"
checkapplepython: $(srcdir)/Tools/fixapplepython23.py
Modified: python/branches/py3k/Mac/README
==============================================================================
--- python/branches/py3k/Mac/README (original)
+++ python/branches/py3k/Mac/README Thu Dec 30 23:12:40 2010
@@ -188,8 +188,8 @@
framework itself, the Mac subtree, the applications and the unix tools.
There is an extra target frameworkinstallextras that is not part of the
-normal frameworkinstall which installs the Demo and Tools directories
-into "/Applications/MacPython <VERSION>", this is useful for binary
+normal frameworkinstall which installs the Tools directory into
+"/Applications/MacPython <VERSION>", this is useful for binary
distributions.
What do all these programs do?
Modified: python/branches/py3k/Makefile.pre.in
==============================================================================
--- python/branches/py3k/Makefile.pre.in (original)
+++ python/branches/py3k/Makefile.pre.in Thu Dec 30 23:12:40 2010
@@ -154,7 +154,7 @@
SRCDIRS= @SRCDIRS@
# Other subdirectories
-SUBDIRSTOO= Include Lib Misc Demo
+SUBDIRSTOO= Include Lib Misc
# Files and directories to be distributed
CONFIGFILES= configure configure.in acconfig.h pyconfig.h.in Makefile.pre.in
@@ -1155,7 +1155,7 @@
frameworkaltinstallunixtools:
cd Mac && $(MAKE) altinstallunixtools DESTDIR="$(DESTDIR)"
-# This installs the Demos and Tools into the applications directory.
+# This installs the Tools into the applications directory.
# It is not part of a normal frameworkinstall
frameworkinstallextras:
cd Mac && $(MAKE) installextras DESTDIR="$(DESTDIR)"
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Thu Dec 30 23:12:40 2010
@@ -79,6 +79,13 @@
- Issue #10679: The "idle", "pydoc" and "2to3" scripts are now installed with
a version-specific suffix on "make altinstall".
+Tools/Demos
+-----------
+
+- Issue #7962: The Demo directory is gone. Most of the old and unmaintained
+ demos have been removed, others integrated in documentation or a new
+ Tools/demo subdirectory.
+
What's New in Python 3.2 Beta 2?
================================
1
0

Dec. 30, 2010
Author: georg.brandl
Date: Thu Dec 30 23:11:50 2010
New Revision: 87585
Log:
Harmonize docstrings. Move redemo from Tools/scripts to Tools/demo. Add a README file to Tools/demo.
Added:
python/branches/py3k/Tools/demo/README
python/branches/py3k/Tools/demo/eiffel.py (contents, props changed)
- copied, changed from r87583, /python/branches/py3k/Tools/demo/Eiffel.py
python/branches/py3k/Tools/demo/redemo.py
- copied unchanged from r87583, /python/branches/py3k/Tools/scripts/redemo.py
python/branches/py3k/Tools/demo/vector.py (contents, props changed)
- copied, changed from r87583, /python/branches/py3k/Tools/demo/Vec.py
Removed:
python/branches/py3k/Tools/demo/Eiffel.py
python/branches/py3k/Tools/demo/Vec.py
python/branches/py3k/Tools/scripts/redemo.py
Modified:
python/branches/py3k/Tools/demo/beer.py
python/branches/py3k/Tools/demo/hanoi.py (contents, props changed)
python/branches/py3k/Tools/demo/life.py
python/branches/py3k/Tools/demo/markov.py
python/branches/py3k/Tools/demo/mcast.py
python/branches/py3k/Tools/demo/queens.py
python/branches/py3k/Tools/demo/rpython.py
python/branches/py3k/Tools/demo/rpythond.py
python/branches/py3k/Tools/demo/sortvisu.py (contents, props changed)
python/branches/py3k/Tools/demo/ss1.py (contents, props changed)
python/branches/py3k/Tools/scripts/README
Deleted: python/branches/py3k/Tools/demo/Eiffel.py
==============================================================================
--- python/branches/py3k/Tools/demo/Eiffel.py Thu Dec 30 23:11:50 2010
+++ (empty file)
@@ -1,141 +0,0 @@
-"""Support Eiffel-style preconditions and postconditions."""
-
-from types import FunctionType as function
-
-class EiffelBaseMetaClass(type):
-
- def __new__(meta, name, bases, dict):
- meta.convert_methods(dict)
- return super(EiffelBaseMetaClass, meta).__new__(meta, name, bases,
- dict)
-
- @classmethod
- def convert_methods(cls, dict):
- """Replace functions in dict with EiffelMethod wrappers.
-
- The dict is modified in place.
-
- If a method ends in _pre or _post, it is removed from the dict
- regardless of whether there is a corresponding method.
- """
- # find methods with pre or post conditions
- methods = []
- for k, v in dict.items():
- if k.endswith('_pre') or k.endswith('_post'):
- assert isinstance(v, function)
- elif isinstance(v, function):
- methods.append(k)
- for m in methods:
- pre = dict.get("%s_pre" % m)
- post = dict.get("%s_post" % m)
- if pre or post:
- dict[k] = cls.make_eiffel_method(dict[m], pre, post)
-
-class EiffelMetaClass1(EiffelBaseMetaClass):
- # an implementation of the "eiffel" meta class that uses nested functions
-
- @staticmethod
- def make_eiffel_method(func, pre, post):
- def method(self, *args, **kwargs):
- if pre:
- pre(self, *args, **kwargs)
- x = func(self, *args, **kwargs)
- if post:
- post(self, x, *args, **kwargs)
- return x
-
- if func.__doc__:
- method.__doc__ = func.__doc__
-
- return method
-
-class EiffelMethodWrapper:
-
- def __init__(self, inst, descr):
- self._inst = inst
- self._descr = descr
-
- def __call__(self, *args, **kwargs):
- return self._descr.callmethod(self._inst, args, kwargs)
-
-class EiffelDescriptor(object):
-
- def __init__(self, func, pre, post):
- self._func = func
- self._pre = pre
- self._post = post
-
- self.__name__ = func.__name__
- self.__doc__ = func.__doc__
-
- def __get__(self, obj, cls):
- return EiffelMethodWrapper(obj, self)
-
- def callmethod(self, inst, args, kwargs):
- if self._pre:
- self._pre(inst, *args, **kwargs)
- x = self._func(inst, *args, **kwargs)
- if self._post:
- self._post(inst, x, *args, **kwargs)
- return x
-
-class EiffelMetaClass2(EiffelBaseMetaClass):
- # an implementation of the "eiffel" meta class that uses descriptors
-
- make_eiffel_method = EiffelDescriptor
-
-def _test(metaclass):
- class Eiffel(metaclass=metaclass):
- pass
-
- class Test(Eiffel):
-
- def m(self, arg):
- """Make it a little larger"""
- return arg + 1
-
- def m2(self, arg):
- """Make it a little larger"""
- return arg + 1
-
- def m2_pre(self, arg):
- assert arg > 0
-
- def m2_post(self, result, arg):
- assert result > arg
-
- class Sub(Test):
- def m2(self, arg):
- return arg**2
- def m2_post(self, Result, arg):
- super(Sub, self).m2_post(Result, arg)
- assert Result < 100
-
- t = Test()
- t.m(1)
- t.m2(1)
- try:
- t.m2(0)
- except AssertionError:
- pass
- else:
- assert False
-
- s = Sub()
- try:
- s.m2(1)
- except AssertionError:
- pass # result == arg
- else:
- assert False
- try:
- s.m2(10)
- except AssertionError:
- pass # result == 100
- else:
- assert False
- s.m2(5)
-
-if __name__ == "__main__":
- _test(EiffelMetaClass1)
- _test(EiffelMetaClass2)
Added: python/branches/py3k/Tools/demo/README
==============================================================================
--- (empty file)
+++ python/branches/py3k/Tools/demo/README Thu Dec 30 23:11:50 2010
@@ -0,0 +1,16 @@
+This directory contains a collection of demonstration scripts for
+various aspects of Python programming.
+
+beer.py Well-known programming example: Bottles of beer.
+eiffel.py Python advanced magic: A metaclass for Eiffel post/preconditions.
+hanoi.py Well-known programming example: Towers of Hanoi.
+life.py Curses programming: Simple game-of-life.
+markov.py Algorithms: Markov chain simulation.
+mcast.py Network programming: Send and receive UDP multicast packets.
+queens.py Well-known programming example: N-Queens problem.
+redemo.py Regular Expressions: GUI script to test regexes.
+rpython.py Network programming: Small client for remote code execution.
+rpythond.py Network programming: Small server for remote code execution.
+sortvisu.py GUI programming: Visualization of different sort algorithms.
+ss1.py GUI/Application programming: A simple spreadsheet application.
+vector.py Python basics: A vector class with demonstrating special methods.
\ No newline at end of file
Deleted: python/branches/py3k/Tools/demo/Vec.py
==============================================================================
--- python/branches/py3k/Tools/demo/Vec.py Thu Dec 30 23:11:50 2010
+++ (empty file)
@@ -1,68 +0,0 @@
-class Vec:
- """ A simple vector class
-
- Instances of the Vec class can be constructed from numbers
-
- >>> a = Vec(1, 2, 3)
- >>> b = Vec(3, 2, 1)
-
- added
- >>> a + b
- Vec(4, 4, 4)
-
- subtracted
- >>> a - b
- Vec(-2, 0, 2)
-
- and multiplied by a scalar on the left
- >>> 3.0 * a
- Vec(3.0, 6.0, 9.0)
-
- or on the right
- >>> a * 3.0
- Vec(3.0, 6.0, 9.0)
- """
- def __init__(self, *v):
- self.v = list(v)
-
- @classmethod
- def fromlist(cls, v):
- if not isinstance(v, list):
- raise TypeError
- inst = cls()
- inst.v = v
- return inst
-
- def __repr__(self):
- args = ', '.join(repr(x) for x in self.v)
- return 'Vec({})'.format(args)
-
- def __len__(self):
- return len(self.v)
-
- def __getitem__(self, i):
- return self.v[i]
-
- def __add__(self, other):
- # Element-wise addition
- v = [x + y for x, y in zip(self.v, other.v)]
- return Vec.fromlist(v)
-
- def __sub__(self, other):
- # Element-wise subtraction
- v = [x - y for x, y in zip(self.v, other.v)]
- return Vec.fromlist(v)
-
- def __mul__(self, scalar):
- # Multiply by scalar
- v = [x * scalar for x in self.v]
- return Vec.fromlist(v)
-
- __rmul__ = __mul__
-
-
-def test():
- import doctest
- doctest.testmod()
-
-test()
Modified: python/branches/py3k/Tools/demo/beer.py
==============================================================================
--- python/branches/py3k/Tools/demo/beer.py (original)
+++ python/branches/py3k/Tools/demo/beer.py Thu Dec 30 23:11:50 2010
@@ -1,6 +1,11 @@
-#! /usr/bin/env python3
+#!/usr/bin/env python3
-# By GvR, demystified after a version by Fredrik Lundh.
+"""
+A Python version of the classic "bottles of beer on the wall" programming
+example.
+
+By Guido van Rossum, demystified after a version by Fredrik Lundh.
+"""
import sys
Copied: python/branches/py3k/Tools/demo/eiffel.py (from r87583, /python/branches/py3k/Tools/demo/Eiffel.py)
==============================================================================
--- /python/branches/py3k/Tools/demo/Eiffel.py (original)
+++ python/branches/py3k/Tools/demo/eiffel.py Thu Dec 30 23:11:50 2010
@@ -1,13 +1,20 @@
-"""Support Eiffel-style preconditions and postconditions."""
+#!/usr/bin/env python3
+"""
+Support Eiffel-style preconditions and postconditions for functions.
+
+An example for Python metaclasses.
+"""
+
+import unittest
from types import FunctionType as function
class EiffelBaseMetaClass(type):
def __new__(meta, name, bases, dict):
meta.convert_methods(dict)
- return super(EiffelBaseMetaClass, meta).__new__(meta, name, bases,
- dict)
+ return super(EiffelBaseMetaClass, meta).__new__(
+ meta, name, bases, dict)
@classmethod
def convert_methods(cls, dict):
@@ -31,6 +38,7 @@
if pre or post:
dict[k] = cls.make_eiffel_method(dict[m], pre, post)
+
class EiffelMetaClass1(EiffelBaseMetaClass):
# an implementation of the "eiffel" meta class that uses nested functions
@@ -39,16 +47,17 @@
def method(self, *args, **kwargs):
if pre:
pre(self, *args, **kwargs)
- x = func(self, *args, **kwargs)
+ rv = func(self, *args, **kwargs)
if post:
- post(self, x, *args, **kwargs)
- return x
+ post(self, rv, *args, **kwargs)
+ return rv
if func.__doc__:
method.__doc__ = func.__doc__
return method
+
class EiffelMethodWrapper:
def __init__(self, inst, descr):
@@ -58,7 +67,8 @@
def __call__(self, *args, **kwargs):
return self._descr.callmethod(self._inst, args, kwargs)
-class EiffelDescriptor(object):
+
+class EiffelDescriptor:
def __init__(self, func, pre, post):
self._func = func
@@ -79,63 +89,58 @@
self._post(inst, x, *args, **kwargs)
return x
+
class EiffelMetaClass2(EiffelBaseMetaClass):
# an implementation of the "eiffel" meta class that uses descriptors
make_eiffel_method = EiffelDescriptor
-def _test(metaclass):
- class Eiffel(metaclass=metaclass):
- pass
-
- class Test(Eiffel):
-
- def m(self, arg):
- """Make it a little larger"""
- return arg + 1
-
- def m2(self, arg):
- """Make it a little larger"""
- return arg + 1
-
- def m2_pre(self, arg):
- assert arg > 0
-
- def m2_post(self, result, arg):
- assert result > arg
-
- class Sub(Test):
- def m2(self, arg):
- return arg**2
- def m2_post(self, Result, arg):
- super(Sub, self).m2_post(Result, arg)
- assert Result < 100
-
- t = Test()
- t.m(1)
- t.m2(1)
- try:
- t.m2(0)
- except AssertionError:
- pass
- else:
- assert False
-
- s = Sub()
- try:
- s.m2(1)
- except AssertionError:
- pass # result == arg
- else:
- assert False
- try:
- s.m2(10)
- except AssertionError:
- pass # result == 100
- else:
- assert False
- s.m2(5)
+
+class Tests(unittest.TestCase):
+
+ def testEiffelMetaClass1(self):
+ self._test(EiffelMetaClass1)
+
+ def testEiffelMetaClass2(self):
+ self._test(EiffelMetaClass2)
+
+ def _test(self, metaclass):
+ class Eiffel(metaclass=metaclass):
+ pass
+
+ class Test(Eiffel):
+ def m(self, arg):
+ """Make it a little larger"""
+ return arg + 1
+
+ def m2(self, arg):
+ """Make it a little larger"""
+ return arg + 1
+
+ def m2_pre(self, arg):
+ assert arg > 0
+
+ def m2_post(self, result, arg):
+ assert result > arg
+
+ class Sub(Test):
+ def m2(self, arg):
+ return arg**2
+
+ def m2_post(self, Result, arg):
+ super(Sub, self).m2_post(Result, arg)
+ assert Result < 100
+
+ t = Test()
+ self.assertEqual(t.m(1), 2)
+ self.assertEqual(t.m2(1), 2)
+ self.assertRaises(AssertionError, t.m2, 0)
+
+ s = Sub()
+ self.assertRaises(AssertionError, s.m2, 1)
+ self.assertRaises(AssertionError, s.m2, 10)
+ self.assertEqual(s.m2(5), 25)
+
if __name__ == "__main__":
- _test(EiffelMetaClass1)
- _test(EiffelMetaClass2)
+ unittest.main()
Modified: python/branches/py3k/Tools/demo/hanoi.py
==============================================================================
--- python/branches/py3k/Tools/demo/hanoi.py (original)
+++ python/branches/py3k/Tools/demo/hanoi.py Thu Dec 30 23:11:50 2010
@@ -1,17 +1,18 @@
-# Animated Towers of Hanoi using Tk with optional bitmap file in
-# background.
-#
-# Usage: tkhanoi [n [bitmapfile]]
-#
-# n is the number of pieces to animate; default is 4, maximum 15.
-#
-# The bitmap file can be any X11 bitmap file (look in
-# /usr/include/X11/bitmaps for samples); it is displayed as the
-# background of the animation. Default is no bitmap.
+#!/usr/bin/env python3
-# This uses Steen Lumholt's Tk interface
-from tkinter import *
+"""
+Animated Towers of Hanoi using Tk with optional bitmap file in background.
+Usage: hanoi.py [n [bitmapfile]]
+
+n is the number of pieces to animate; default is 4, maximum 15.
+
+The bitmap file can be any X11 bitmap file (look in /usr/include/X11/bitmaps for
+samples); it is displayed as the background of the animation. Default is no
+bitmap.
+"""
+
+from tkinter import Tk, Canvas
# Basic Towers-of-Hanoi algorithm: move n pieces from a to b, using c
# as temporary. For each move, call report()
@@ -123,7 +124,6 @@
self.pegstate[b].append(i)
-# Main program
def main():
import sys
Modified: python/branches/py3k/Tools/demo/life.py
==============================================================================
--- python/branches/py3k/Tools/demo/life.py (original)
+++ python/branches/py3k/Tools/demo/life.py Thu Dec 30 23:11:50 2010
@@ -1,23 +1,23 @@
#!/usr/bin/env python3
-# life.py -- A curses-based version of Conway's Game of Life.
-# Contributed by AMK
-# Mouse support and color by Dafydd Crosby
-#
-# An empty board will be displayed, and the following commands are available:
-# E : Erase the board
-# R : Fill the board randomly
-# S : Step for a single generation
-# C : Update continuously until a key is struck
-# Q : Quit
-# Cursor keys : Move the cursor around the board
-# Space or Enter : Toggle the contents of the cursor's position
-#
-# TODO :
-# Make board updates faster
-#
-import random, string, traceback
+"""
+A curses-based version of Conway's Game of Life.
+
+An empty board will be displayed, and the following commands are available:
+ E : Erase the board
+ R : Fill the board randomly
+ S : Step for a single generation
+ C : Update continuously until a key is struck
+ Q : Quit
+ Cursor keys : Move the cursor around the board
+ Space or Enter : Toggle the contents of the cursor's position
+
+Contributed by Andrew Kuchling, Mouse support and color by Dafydd Crosby.
+"""
+
import curses
+import random
+
class LifeBoard:
"""Encapsulates a Life board
@@ -31,7 +31,7 @@
next generation. Then display the state
of the board and refresh the screen.
erase() -- clear the entire board
- makeRandom() -- fill the board randomly
+ make_random() -- fill the board randomly
set(y,x) -- set the given cell to Live; doesn't refresh the screen
toggle(y,x) -- change the given cell from live to dead, or vice
versa, and refresh the screen display
@@ -53,7 +53,7 @@
# Draw a border around the board
border_line = '+'+(self.X*'-')+'+'
self.scr.addstr(0, 0, border_line)
- self.scr.addstr(self.Y+1,0, border_line)
+ self.scr.addstr(self.Y+1, 0, border_line)
for y in range(0, self.Y):
self.scr.addstr(1+y, 0, '|')
self.scr.addstr(1+y, self.X+1, '|')
@@ -62,21 +62,21 @@
def set(self, y, x):
"""Set a cell to the live state"""
if x<0 or self.X<=x or y<0 or self.Y<=y:
- raise ValueError("Coordinates out of range %i,%i"% (y,x))
+ raise ValueError("Coordinates out of range %i,%i"% (y, x))
self.state[x,y] = 1
def toggle(self, y, x):
"""Toggle a cell's state between live and dead"""
- if x<0 or self.X<=x or y<0 or self.Y<=y:
- raise ValueError("Coordinates out of range %i,%i"% (y,x))
- if (x,y) in self.state:
- del self.state[x,y]
+ if x < 0 or self.X <= x or y < 0 or self.Y <= y:
+ raise ValueError("Coordinates out of range %i,%i"% (y, x))
+ if (x, y) in self.state:
+ del self.state[x, y]
self.scr.addch(y+1, x+1, ' ')
else:
- self.state[x,y] = 1
+ self.state[x, y] = 1
if curses.has_colors():
- #Let's pick a random color!
- self.scr.attrset(curses.color_pair(random.randrange(1,7)))
+ # Let's pick a random color!
+ self.scr.attrset(curses.color_pair(random.randrange(1, 7)))
self.scr.addch(y+1, x+1, self.char)
self.scr.attrset(0)
self.scr.refresh()
@@ -115,8 +115,9 @@
# Birth
d[i,j] = 1
if curses.has_colors():
- #Let's pick a random color!
- self.scr.attrset(curses.color_pair(random.randrange(1,7)))
+ # Let's pick a random color!
+ self.scr.attrset(curses.color_pair(
+ random.randrange(1, 7)))
self.scr.addch(j+1, i+1, self.char)
self.scr.attrset(0)
if not live: self.boring = 0
@@ -128,7 +129,7 @@
self.state = d
self.scr.refresh()
- def makeRandom(self):
+ def make_random(self):
"Fill the board with a random pattern"
self.state = {}
for i in range(0, self.X):
@@ -152,9 +153,9 @@
if curses.has_colors():
stdscr.attrset(curses.color_pair(1))
stdscr.addstr(menu_y, 4,
- 'Use the cursor keys to move, and space or Enter to toggle a cell.')
+ 'Use the cursor keys to move, and space or Enter to toggle a cell.')
stdscr.addstr(menu_y+1, 4,
- 'E)rase the board, R)andom fill, S)tep once or C)ontinuously, Q)uit')
+ 'E)rase the board, R)andom fill, S)tep once or C)ontinuously, Q)uit')
stdscr.attrset(0)
def keyloop(stdscr):
@@ -186,10 +187,10 @@
xpos, ypos = board.X//2, board.Y//2
# Main loop:
- while (1):
+ while True:
stdscr.move(1+ypos, 1+xpos) # Move the cursor
c = stdscr.getch() # Get a keystroke
- if 0<c<256:
+ if 0 < c < 256:
c = chr(c)
if c in ' \n':
board.toggle(ypos, xpos)
@@ -201,14 +202,14 @@
# Activate nodelay mode; getch() will return -1
# if no keystroke is available, instead of waiting.
stdscr.nodelay(1)
- while (1):
+ while True:
c = stdscr.getch()
if c != -1:
break
- stdscr.addstr(0,0, '/')
+ stdscr.addstr(0, 0, '/')
stdscr.refresh()
board.display()
- stdscr.addstr(0,0, '+')
+ stdscr.addstr(0, 0, '+')
stdscr.refresh()
stdscr.nodelay(0) # Disable nodelay mode
@@ -219,18 +220,19 @@
elif c in 'Qq':
break
elif c in 'Rr':
- board.makeRandom()
+ board.make_random()
board.display(update_board=False)
elif c in 'Ss':
board.display()
else: pass # Ignore incorrect keys
- elif c == curses.KEY_UP and ypos>0: ypos -= 1
- elif c == curses.KEY_DOWN and ypos<board.Y-1: ypos += 1
- elif c == curses.KEY_LEFT and xpos>0: xpos -= 1
- elif c == curses.KEY_RIGHT and xpos<board.X-1: xpos += 1
+ elif c == curses.KEY_UP and ypos > 0: ypos -= 1
+ elif c == curses.KEY_DOWN and ypos < board.Y-1: ypos += 1
+ elif c == curses.KEY_LEFT and xpos > 0: xpos -= 1
+ elif c == curses.KEY_RIGHT and xpos < board.X-1: xpos += 1
elif c == curses.KEY_MOUSE:
- (mouse_id, mouse_x, mouse_y, mouse_z, button_state) = curses.getmouse()
- if (mouse_x>0 and mouse_x<board.X+1) and (mouse_y>0 and mouse_y<board.Y+1):
+ mouse_id, mouse_x, mouse_y, mouse_z, button_state = curses.getmouse()
+ if (mouse_x > 0 and mouse_x < board.X+1 and
+ mouse_y > 0 and mouse_y < board.Y+1):
xpos = mouse_x - 1
ypos = mouse_y - 1
board.toggle(ypos, xpos)
@@ -245,6 +247,5 @@
def main(stdscr):
keyloop(stdscr) # Enter the main loop
-
if __name__ == '__main__':
curses.wrapper(main)
Modified: python/branches/py3k/Tools/demo/markov.py
==============================================================================
--- python/branches/py3k/Tools/demo/markov.py (original)
+++ python/branches/py3k/Tools/demo/markov.py Thu Dec 30 23:11:50 2010
@@ -1,4 +1,8 @@
-#! /usr/bin/env python3
+#!/usr/bin/env python3
+
+"""
+Markov chain simulation of words or characters.
+"""
class Markov:
def __init__(self, histsize, choice):
Modified: python/branches/py3k/Tools/demo/mcast.py
==============================================================================
--- python/branches/py3k/Tools/demo/mcast.py (original)
+++ python/branches/py3k/Tools/demo/mcast.py Thu Dec 30 23:11:50 2010
@@ -1,13 +1,15 @@
#!/usr/bin/env python3
-#
-# Send/receive UDP multicast packets.
-# Requires that your OS kernel supports IP multicast.
-#
-# Usage:
-# mcast -s (sender, IPv4)
-# mcast -s -6 (sender, IPv6)
-# mcast (receivers, IPv4)
-# mcast -6 (receivers, IPv6)
+
+"""
+Send/receive UDP multicast packets.
+Requires that your OS kernel supports IP multicast.
+
+Usage:
+ mcast -s (sender, IPv4)
+ mcast -s -6 (sender, IPv6)
+ mcast (receivers, IPv4)
+ mcast -6 (receivers, IPv6)
+"""
MYPORT = 8123
MYGROUP_4 = '225.0.0.250'
Modified: python/branches/py3k/Tools/demo/queens.py
==============================================================================
--- python/branches/py3k/Tools/demo/queens.py (original)
+++ python/branches/py3k/Tools/demo/queens.py Thu Dec 30 23:11:50 2010
@@ -1,12 +1,12 @@
-#! /usr/bin/env python3
+#!/usr/bin/env python3
-"""N queens problem.
+"""
+N queens problem.
The (well-known) problem is due to Niklaus Wirth.
This solution is inspired by Dijkstra (Structured Programming). It is
a classic recursive backtracking approach.
-
"""
N = 8 # Default; command line overrides
Modified: python/branches/py3k/Tools/demo/rpython.py
==============================================================================
--- python/branches/py3k/Tools/demo/rpython.py (original)
+++ python/branches/py3k/Tools/demo/rpython.py Thu Dec 30 23:11:50 2010
@@ -1,7 +1,9 @@
-#! /usr/bin/env python3
+#!/usr/bin/env python3
-# Remote python client.
-# Execute Python commands remotely and send output back.
+"""
+Remote python client.
+Execute Python commands remotely and send output back.
+"""
import sys
from socket import socket, AF_INET, SOCK_STREAM, SHUT_WR
Modified: python/branches/py3k/Tools/demo/rpythond.py
==============================================================================
--- python/branches/py3k/Tools/demo/rpythond.py (original)
+++ python/branches/py3k/Tools/demo/rpythond.py Thu Dec 30 23:11:50 2010
@@ -1,9 +1,12 @@
-#! /usr/bin/env python3
+#!/usr/bin/env python3
-# Remote python server.
-# Execute Python commands remotely and send output back.
-# WARNING: This version has a gaping security hole -- it accepts requests
-# from any host on the Internet!
+"""
+Remote python server.
+Execute Python commands remotely and send output back.
+
+WARNING: This version has a gaping security hole -- it accepts requests
+from any host on the Internet!
+"""
import sys
from socket import socket, AF_INET, SOCK_STREAM
Modified: python/branches/py3k/Tools/demo/sortvisu.py
==============================================================================
--- python/branches/py3k/Tools/demo/sortvisu.py (original)
+++ python/branches/py3k/Tools/demo/sortvisu.py Thu Dec 30 23:11:50 2010
@@ -1,6 +1,7 @@
-#! /usr/bin/env python3
+#!/usr/bin/env python3
-"""Sorting algorithms visualizer using Tkinter.
+"""
+Sorting algorithms visualizer using Tkinter.
This module is comprised of three ``components'':
@@ -15,13 +16,11 @@
- and a ``driver'' class which can be used as a Grail applet or as a
stand-alone application.
-
"""
from tkinter import *
import random
-
XGRID = 10
YGRID = 10
WIDTH = 6
Modified: python/branches/py3k/Tools/demo/ss1.py
==============================================================================
--- python/branches/py3k/Tools/demo/ss1.py (original)
+++ python/branches/py3k/Tools/demo/ss1.py Thu Dec 30 23:11:50 2010
@@ -1,4 +1,8 @@
-"""SS1 -- a spreadsheet."""
+#!/usr/bin/env python3
+
+"""
+SS1 -- a spreadsheet-like application.
+"""
import os
import re
Copied: python/branches/py3k/Tools/demo/vector.py (from r87583, /python/branches/py3k/Tools/demo/Vec.py)
==============================================================================
--- /python/branches/py3k/Tools/demo/Vec.py (original)
+++ python/branches/py3k/Tools/demo/vector.py Thu Dec 30 23:11:50 2010
@@ -1,7 +1,13 @@
+#!/usr/bin/env python3
+
+"""
+A demonstration of classes and their special methods in Python.
+"""
+
class Vec:
- """ A simple vector class
+ """A simple vector class.
- Instances of the Vec class can be constructed from numbers
+ Instances of the Vec class can be constructed from numbers
>>> a = Vec(1, 2, 3)
>>> b = Vec(3, 2, 1)
Modified: python/branches/py3k/Tools/scripts/README
==============================================================================
--- python/branches/py3k/Tools/scripts/README (original)
+++ python/branches/py3k/Tools/scripts/README Thu Dec 30 23:11:50 2010
@@ -2,8 +2,6 @@
useful while building, extending or managing Python. Some (e.g., dutree or lll)
are also generally useful UNIX tools.
-See also the Demo/scripts directory!
-
2to3 Main script for running the 2to3 conversion tool
analyze_dxp.py Analyzes the result of sys.getdxp()
byext.py Print lines/words/chars stats of files by extension
Deleted: python/branches/py3k/Tools/scripts/redemo.py
==============================================================================
--- python/branches/py3k/Tools/scripts/redemo.py Thu Dec 30 23:11:50 2010
+++ (empty file)
@@ -1,171 +0,0 @@
-"""Basic regular expression demostration facility (Perl style syntax)."""
-
-from tkinter import *
-import re
-
-class ReDemo:
-
- def __init__(self, master):
- self.master = master
-
- self.promptdisplay = Label(self.master, anchor=W,
- text="Enter a Perl-style regular expression:")
- self.promptdisplay.pack(side=TOP, fill=X)
-
- self.regexdisplay = Entry(self.master)
- self.regexdisplay.pack(fill=X)
- self.regexdisplay.focus_set()
-
- self.addoptions()
-
- self.statusdisplay = Label(self.master, text="", anchor=W)
- self.statusdisplay.pack(side=TOP, fill=X)
-
- self.labeldisplay = Label(self.master, anchor=W,
- text="Enter a string to search:")
- self.labeldisplay.pack(fill=X)
- self.labeldisplay.pack(fill=X)
-
- self.showframe = Frame(master)
- self.showframe.pack(fill=X, anchor=W)
-
- self.showvar = StringVar(master)
- self.showvar.set("first")
-
- self.showfirstradio = Radiobutton(self.showframe,
- text="Highlight first match",
- variable=self.showvar,
- value="first",
- command=self.recompile)
- self.showfirstradio.pack(side=LEFT)
-
- self.showallradio = Radiobutton(self.showframe,
- text="Highlight all matches",
- variable=self.showvar,
- value="all",
- command=self.recompile)
- self.showallradio.pack(side=LEFT)
-
- self.stringdisplay = Text(self.master, width=60, height=4)
- self.stringdisplay.pack(fill=BOTH, expand=1)
- self.stringdisplay.tag_configure("hit", background="yellow")
-
- self.grouplabel = Label(self.master, text="Groups:", anchor=W)
- self.grouplabel.pack(fill=X)
-
- self.grouplist = Listbox(self.master)
- self.grouplist.pack(expand=1, fill=BOTH)
-
- self.regexdisplay.bind('<Key>', self.recompile)
- self.stringdisplay.bind('<Key>', self.reevaluate)
-
- self.compiled = None
- self.recompile()
-
- btags = self.regexdisplay.bindtags()
- self.regexdisplay.bindtags(btags[1:] + btags[:1])
-
- btags = self.stringdisplay.bindtags()
- self.stringdisplay.bindtags(btags[1:] + btags[:1])
-
- def addoptions(self):
- self.frames = []
- self.boxes = []
- self.vars = []
- for name in ('IGNORECASE',
- 'LOCALE',
- 'MULTILINE',
- 'DOTALL',
- 'VERBOSE'):
- if len(self.boxes) % 3 == 0:
- frame = Frame(self.master)
- frame.pack(fill=X)
- self.frames.append(frame)
- val = getattr(re, name)
- var = IntVar()
- box = Checkbutton(frame,
- variable=var, text=name,
- offvalue=0, onvalue=val,
- command=self.recompile)
- box.pack(side=LEFT)
- self.boxes.append(box)
- self.vars.append(var)
-
- def getflags(self):
- flags = 0
- for var in self.vars:
- flags = flags | var.get()
- flags = flags
- return flags
-
- def recompile(self, event=None):
- try:
- self.compiled = re.compile(self.regexdisplay.get(),
- self.getflags())
- bg = self.promptdisplay['background']
- self.statusdisplay.config(text="", background=bg)
- except re.error as msg:
- self.compiled = None
- self.statusdisplay.config(
- text="re.error: %s" % str(msg),
- background="red")
- self.reevaluate()
-
- def reevaluate(self, event=None):
- try:
- self.stringdisplay.tag_remove("hit", "1.0", END)
- except TclError:
- pass
- try:
- self.stringdisplay.tag_remove("hit0", "1.0", END)
- except TclError:
- pass
- self.grouplist.delete(0, END)
- if not self.compiled:
- return
- self.stringdisplay.tag_configure("hit", background="yellow")
- self.stringdisplay.tag_configure("hit0", background="orange")
- text = self.stringdisplay.get("1.0", END)
- last = 0
- nmatches = 0
- while last <= len(text):
- m = self.compiled.search(text, last)
- if m is None:
- break
- first, last = m.span()
- if last == first:
- last = first+1
- tag = "hit0"
- else:
- tag = "hit"
- pfirst = "1.0 + %d chars" % first
- plast = "1.0 + %d chars" % last
- self.stringdisplay.tag_add(tag, pfirst, plast)
- if nmatches == 0:
- self.stringdisplay.yview_pickplace(pfirst)
- groups = list(m.groups())
- groups.insert(0, m.group())
- for i in range(len(groups)):
- g = "%2d: %r" % (i, groups[i])
- self.grouplist.insert(END, g)
- nmatches = nmatches + 1
- if self.showvar.get() == "first":
- break
-
- if nmatches == 0:
- self.statusdisplay.config(text="(no match)",
- background="yellow")
- else:
- self.statusdisplay.config(text="")
-
-
-# Main function, run when invoked as a stand-alone Python program.
-
-def main():
- root = Tk()
- demo = ReDemo(root)
- root.protocol('WM_DELETE_WINDOW', root.quit)
- root.mainloop()
-
-if __name__ == '__main__':
- main()
1
0
Author: georg.brandl
Date: Thu Dec 30 22:33:49 2010
New Revision: 87584
Log:
Remove the actual Demo dir.
Removed:
python/branches/py3k/Demo/
1
0
Author: georg.brandl
Date: Thu Dec 30 22:33:07 2010
New Revision: 87583
Log:
More cleanup: Move some demos into a dedicated Tools/demo dir, move 2to3 demo to Tools, and remove all the other Demo content.
Added:
python/branches/py3k/Tools/demo/
python/branches/py3k/Tools/demo/Eiffel.py
- copied unchanged from r87579, /python/branches/py3k/Demo/newmetaclasses/Eiffel.py
python/branches/py3k/Tools/demo/Vec.py
- copied unchanged from r87579, /python/branches/py3k/Demo/classes/Vec.py
python/branches/py3k/Tools/demo/beer.py
- copied unchanged from r87579, /python/branches/py3k/Demo/scripts/beer.py
python/branches/py3k/Tools/demo/hanoi.py
- copied unchanged from r87579, /python/branches/py3k/Demo/tkinter/guido/hanoi.py
python/branches/py3k/Tools/demo/life.py
- copied unchanged from r87579, /python/branches/py3k/Demo/curses/life.py
python/branches/py3k/Tools/demo/markov.py
- copied unchanged from r87579, /python/branches/py3k/Demo/scripts/markov.py
python/branches/py3k/Tools/demo/mcast.py
- copied unchanged from r87579, /python/branches/py3k/Demo/sockets/mcast.py
python/branches/py3k/Tools/demo/queens.py
- copied unchanged from r87579, /python/branches/py3k/Demo/scripts/queens.py
python/branches/py3k/Tools/demo/rpython.py
- copied, changed from r87579, /python/branches/py3k/Demo/sockets/rpython.py
python/branches/py3k/Tools/demo/rpythond.py
- copied, changed from r87579, /python/branches/py3k/Demo/sockets/rpythond.py
python/branches/py3k/Tools/demo/sortvisu.py
- copied unchanged from r87579, /python/branches/py3k/Demo/tkinter/guido/sortvisu.py
python/branches/py3k/Tools/demo/ss1.py
- copied unchanged from r87579, /python/branches/py3k/Demo/tkinter/guido/ss1.py
python/branches/py3k/Tools/test2to3/
- copied from r87579, /python/branches/py3k/Demo/distutils/test2to3/
Removed:
python/branches/py3k/Demo/README
python/branches/py3k/Demo/classes/
python/branches/py3k/Demo/curses/
python/branches/py3k/Demo/distutils/test2to3/
python/branches/py3k/Demo/embed/
python/branches/py3k/Demo/newmetaclasses/
python/branches/py3k/Demo/scripts/
python/branches/py3k/Demo/sockets/
python/branches/py3k/Demo/tix/
python/branches/py3k/Demo/tkinter/
Deleted: python/branches/py3k/Demo/README
==============================================================================
--- python/branches/py3k/Demo/README Thu Dec 30 22:33:07 2010
+++ (empty file)
@@ -1,62 +0,0 @@
-This directory contains various demonstrations of what you can do with
-Python. They were all written by me except where explicitly stated
-otherwise -- in general, demos contributed by others ends up in the
-../Contrib directory, unless I think they're of utmost general
-importance (like Matt Conway's Tk demos).
-
-A fair number of utilities that are useful when while developing
-Python code can be found in the ../Tools directory -- some of these
-can also be considered good examples of how to write Python code.
-
-Finally, in order to save disk space and net bandwidth, not all
-subdirectories listed here are distributed. They are listed just
-in case I change my mind about them.
-
-
-cgi CGI examples.
-
-classes Some examples of how to use classes.
-
-comparisons A set of responses to a really old language-comparison
- challenge.
-
-curses A set of curses demos.
-
-distutils Test for using transparent 2to3 conversion in distutils.
-
-embed An example of embedding Python in another application
- (see also pysvr).
-
-imputil Demonstration subclasses of imputil.Importer.
-
-md5test Test program for the optional md5 module.
-
-newmetaclasses Demonstration of metaclasses.
-
-parser Example using the parser module.
-
-pysvr An example of embedding Python in a threaded
- application.
-
-rpc A set of classes for building clients and servers for
- Sun RPC.
-
-scripts Some useful Python scripts that I put in my bin
- directory. No optional built-in modules needed.
-
-sockets Examples for the new built-in module 'socket'.
-
-threads Demos that use the 'thread' module. (Currently these
- only run on SGIs, but this may change in the future.)
-
-tix Demos using the Tix widget set addition to Tkinter.
-
-tkinter Demos using the Tk interface (including Matt Conway's
- excellent set of demos).
-
-turtle Demos for the "turtle" module.
-
-xml Some XML demos.
-
-zlib Some demos for the zlib module (see also the standard
- library module gzip.py).
Copied: python/branches/py3k/Tools/demo/rpython.py (from r87579, /python/branches/py3k/Demo/sockets/rpython.py)
==============================================================================
--- /python/branches/py3k/Demo/sockets/rpython.py (original)
+++ python/branches/py3k/Tools/demo/rpython.py Thu Dec 30 22:33:07 2010
@@ -4,8 +4,7 @@
# Execute Python commands remotely and send output back.
import sys
-import string
-from socket import *
+from socket import socket, AF_INET, SOCK_STREAM, SHUT_WR
PORT = 4127
BUFSIZE = 1024
@@ -16,20 +15,22 @@
sys.exit(2)
host = sys.argv[1]
port = PORT
- i = string.find(host, ':')
+ i = host.find(':')
if i >= 0:
- port = string.atoi(port[i+1:])
+ port = int(port[i+1:])
host = host[:i]
- command = string.join(sys.argv[2:])
+ command = ' '.join(sys.argv[2:])
s = socket(AF_INET, SOCK_STREAM)
s.connect((host, port))
- s.send(command)
- s.shutdown(1)
- reply = ''
- while 1:
+ s.send(command.encode())
+ s.shutdown(SHUT_WR)
+ reply = b''
+ while True:
data = s.recv(BUFSIZE)
- if not data: break
- reply = reply + data
- print(reply, end=' ')
+ if not data:
+ break
+ reply += data
+ print(reply.decode(), end=' ')
+ s.close()
main()
Copied: python/branches/py3k/Tools/demo/rpythond.py (from r87579, /python/branches/py3k/Demo/sockets/rpythond.py)
==============================================================================
--- /python/branches/py3k/Demo/sockets/rpythond.py (original)
+++ python/branches/py3k/Tools/demo/rpythond.py Thu Dec 30 22:33:07 2010
@@ -6,7 +6,7 @@
# from any host on the Internet!
import sys
-from socket import *
+from socket import socket, AF_INET, SOCK_STREAM
import io
import traceback
@@ -15,23 +15,23 @@
def main():
if len(sys.argv) > 1:
- port = int(eval(sys.argv[1]))
+ port = int(sys.argv[1])
else:
port = PORT
s = socket(AF_INET, SOCK_STREAM)
s.bind(('', port))
s.listen(1)
- while 1:
+ while True:
conn, (remotehost, remoteport) = s.accept()
- print('connected by', remotehost, remoteport)
- request = ''
+ print('connection from', remotehost, remoteport)
+ request = b''
while 1:
data = conn.recv(BUFSIZE)
if not data:
break
- request = request + data
- reply = execute(request)
- conn.send(reply)
+ request += data
+ reply = execute(request.decode())
+ conn.send(reply.encode())
conn.close()
def execute(request):
@@ -49,4 +49,7 @@
sys.stdout = stdout
return fakefile.getvalue()
-main()
+try:
+ main()
+except KeyboardInterrupt:
+ pass
1
0

r87582 - in python/branches/py3k: Lib/unittest/runner.py Lib/unittest/test/test_runner.py Misc/NEWS
by michael.foord Dec. 30, 2010
by michael.foord Dec. 30, 2010
Dec. 30, 2010
Author: michael.foord
Date: Thu Dec 30 20:36:29 2010
New Revision: 87582
Log:
Issue 10786: unittest.TextTestRunner default stream no longer bound at import time
Modified:
python/branches/py3k/Lib/unittest/runner.py
python/branches/py3k/Lib/unittest/test/test_runner.py
python/branches/py3k/Misc/NEWS
Modified: python/branches/py3k/Lib/unittest/runner.py
==============================================================================
--- python/branches/py3k/Lib/unittest/runner.py (original)
+++ python/branches/py3k/Lib/unittest/runner.py Thu Dec 30 20:36:29 2010
@@ -125,8 +125,10 @@
"""
resultclass = TextTestResult
- def __init__(self, stream=sys.stderr, descriptions=True, verbosity=1,
+ def __init__(self, stream=None, descriptions=True, verbosity=1,
failfast=False, buffer=False, resultclass=None, warnings=None):
+ if stream is None:
+ stream = sys.stderr
self.stream = _WritelnDecorator(stream)
self.descriptions = descriptions
self.verbosity = verbosity
Modified: python/branches/py3k/Lib/unittest/test/test_runner.py
==============================================================================
--- python/branches/py3k/Lib/unittest/test/test_runner.py (original)
+++ python/branches/py3k/Lib/unittest/test/test_runner.py Thu Dec 30 20:36:29 2010
@@ -299,3 +299,20 @@
self.assertEqual(out.count(msg), 3)
for msg in [ae_msg, at_msg]:
self.assertEqual(out.count(msg), 1)
+
+ def testStdErrLookedUpAtInstantiationTime(self):
+ # see issue 10786
+ old_stderr = sys.stderr
+ f = io.StringIO()
+ sys.stderr = f
+ try:
+ runner = unittest.TextTestRunner()
+ self.assertTrue(runner.stream.stream is f)
+ finally:
+ sys.stderr = old_stderr
+
+ def testSpecifiedStreamUsed(self):
+ # see issue 10786
+ f = io.StringIO()
+ runner = unittest.TextTestRunner(f)
+ self.assertTrue(runner.stream.stream is f)
Modified: python/branches/py3k/Misc/NEWS
==============================================================================
--- python/branches/py3k/Misc/NEWS (original)
+++ python/branches/py3k/Misc/NEWS Thu Dec 30 20:36:29 2010
@@ -20,6 +20,10 @@
Library
-------
+- Issue 10786: unittest.TextTestRunner default stream no longer bound at
+ import time. `sys.stderr` now looked up at instantiation time. Fix contributed
+ by Mark Roddy.
+
- Issue 10753 - Characters ';','=' and ',' in the PATH_INFO environment
variable won't be quoted when the URI is constructed by the wsgiref.util 's
request_uri method. According to RFC 3986, these characters can be a part of
1
0

Dec. 30, 2010
Author: georg.brandl
Date: Thu Dec 30 18:36:17 2010
New Revision: 87581
Log:
Fix NameErrors.
Modified:
python/branches/py3k/Tools/scripts/get-remote-certificate.py
Modified: python/branches/py3k/Tools/scripts/get-remote-certificate.py
==============================================================================
--- python/branches/py3k/Tools/scripts/get-remote-certificate.py (original)
+++ python/branches/py3k/Tools/scripts/get-remote-certificate.py Thu Dec 30 18:36:17 2010
@@ -8,7 +8,6 @@
import re
import os
-import ssl
import sys
import tempfile
@@ -38,7 +37,8 @@
status, output = subproc(r'openssl x509 -in "%s" -out "%s"' %
(tn, tn2))
if status != 0:
- raise OperationError(status, tsig, output)
+ raise RuntimeError('OpenSSL x509 failed with status %s and '
+ 'output: %r' % (status, output))
fp = open(tn2, 'rb')
data = fp.read()
fp.close()
@@ -63,7 +63,8 @@
'openssl s_client -connect "%s:%s" -showcerts < /dev/null' %
(host, port))
if status != 0:
- raise OSError(status)
+ raise RuntimeError('OpenSSL connect failed with status %s and '
+ 'output: %r' % (status, output))
certtext = strip_to_x509_cert(output)
if not certtext:
raise ValueError("Invalid response received from server at %s:%s" %
1
0

r87580 - in python/branches/py3k/Tools: framer scripts/get-remote-certificate.py ssl/get-remote-certificate.py world
by georg.brandl Dec. 30, 2010
by georg.brandl Dec. 30, 2010
Dec. 30, 2010
Author: georg.brandl
Date: Thu Dec 30 18:32:22 2010
New Revision: 87580
Log:
Clean up tools: remove "world" and "framer", move single SSL script to scripts/.
Added:
python/branches/py3k/Tools/scripts/get-remote-certificate.py
- copied unchanged from r87579, /python/branches/py3k/Tools/ssl/get-remote-certificate.py
Removed:
python/branches/py3k/Tools/framer/
python/branches/py3k/Tools/ssl/get-remote-certificate.py
python/branches/py3k/Tools/world/
Deleted: python/branches/py3k/Tools/ssl/get-remote-certificate.py
==============================================================================
--- python/branches/py3k/Tools/ssl/get-remote-certificate.py Thu Dec 30 18:32:22 2010
+++ (empty file)
@@ -1,83 +0,0 @@
-#!/usr/bin/env python3
-#
-# fetch the certificate that the server(s) are providing in PEM form
-#
-# args are HOST:PORT [, HOST:PORT...]
-#
-# By Bill Janssen.
-
-import re
-import os
-import ssl
-import sys
-import tempfile
-
-
-def fetch_server_certificate (host, port):
-
- def subproc(cmd):
- from subprocess import Popen, PIPE, STDOUT
- proc = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
- status = proc.wait()
- output = proc.stdout.read()
- return status, output
-
- def strip_to_x509_cert(certfile_contents, outfile=None):
- m = re.search(br"^([-]+BEGIN CERTIFICATE[-]+[\r]*\n"
- br".*[\r]*^[-]+END CERTIFICATE[-]+)$",
- certfile_contents, re.MULTILINE | re.DOTALL)
- if not m:
- return None
- else:
- tn = tempfile.mktemp()
- fp = open(tn, "wb")
- fp.write(m.group(1) + b"\n")
- fp.close()
- try:
- tn2 = (outfile or tempfile.mktemp())
- status, output = subproc(r'openssl x509 -in "%s" -out "%s"' %
- (tn, tn2))
- if status != 0:
- raise OperationError(status, tsig, output)
- fp = open(tn2, 'rb')
- data = fp.read()
- fp.close()
- os.unlink(tn2)
- return data
- finally:
- os.unlink(tn)
-
- if sys.platform.startswith("win"):
- tfile = tempfile.mktemp()
- fp = open(tfile, "w")
- fp.write("quit\n")
- fp.close()
- try:
- status, output = subproc(
- 'openssl s_client -connect "%s:%s" -showcerts < "%s"' %
- (host, port, tfile))
- finally:
- os.unlink(tfile)
- else:
- status, output = subproc(
- 'openssl s_client -connect "%s:%s" -showcerts < /dev/null' %
- (host, port))
- if status != 0:
- raise OSError(status)
- certtext = strip_to_x509_cert(output)
- if not certtext:
- raise ValueError("Invalid response received from server at %s:%s" %
- (host, port))
- return certtext
-
-
-if __name__ == "__main__":
- if len(sys.argv) < 2:
- sys.stderr.write(
- "Usage: %s HOSTNAME:PORTNUMBER [, HOSTNAME:PORTNUMBER...]\n" %
- sys.argv[0])
- sys.exit(1)
- for arg in sys.argv[1:]:
- host, port = arg.split(":")
- sys.stdout.buffer.write(fetch_server_certificate(host, int(port)))
- sys.exit(0)
1
0
Author: georg.brandl
Date: Thu Dec 30 18:22:33 2010
New Revision: 87579
Log:
Remove some of the old demos. (Put a few somewhere else.)
Added:
python/branches/py3k/Tools/parser/
python/branches/py3k/Tools/parser/test_unparse.py
- copied unchanged from r87578, /python/branches/py3k/Demo/parser/test_unparse.py
python/branches/py3k/Tools/parser/unparse.py
- copied unchanged from r87578, /python/branches/py3k/Demo/parser/unparse.py
python/branches/py3k/Tools/scripts/find-uname.py
- copied unchanged from r87578, /python/branches/py3k/Demo/scripts/find-uname.py
Removed:
python/branches/py3k/Demo/cgi/
python/branches/py3k/Demo/comparisons/
python/branches/py3k/Demo/curses/ncurses.py
python/branches/py3k/Demo/curses/rain.py
python/branches/py3k/Demo/curses/tclock.py
python/branches/py3k/Demo/curses/xmas.py
python/branches/py3k/Demo/md5test/
python/branches/py3k/Demo/parser/
python/branches/py3k/Demo/pysvr/
python/branches/py3k/Demo/rpc/
python/branches/py3k/Demo/scripts/eqfix.py
python/branches/py3k/Demo/scripts/find-uname.py
python/branches/py3k/Demo/scripts/from.py
python/branches/py3k/Demo/scripts/lpwatch.py
python/branches/py3k/Demo/scripts/makedir.py
python/branches/py3k/Demo/scripts/mboxconvert.py
python/branches/py3k/Demo/scripts/morse.py
python/branches/py3k/Demo/scripts/newslist.doc
python/branches/py3k/Demo/scripts/newslist.py
python/branches/py3k/Demo/scripts/pi.py
python/branches/py3k/Demo/scripts/pp.py
python/branches/py3k/Demo/scripts/primes.py
python/branches/py3k/Demo/scripts/script.py
python/branches/py3k/Demo/scripts/update.py
python/branches/py3k/Demo/threads/
python/branches/py3k/Demo/xml/
python/branches/py3k/Demo/zlib/
Modified:
python/branches/py3k/Doc/library/pty.rst
Deleted: python/branches/py3k/Demo/curses/ncurses.py
==============================================================================
--- python/branches/py3k/Demo/curses/ncurses.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,273 +0,0 @@
-#!/usr/bin/env python3
-#
-# $Id$
-#
-# (n)curses exerciser in Python, an interactive test for the curses
-# module. Currently, only the panel demos are ported.
-
-import curses
-from curses import panel
-
-def wGetchar(win = None):
- if win is None: win = stdscr
- return win.getch()
-
-def Getchar():
- wGetchar()
-
-#
-# Panels tester
-#
-def wait_a_while():
- if nap_msec == 1:
- Getchar()
- else:
- curses.napms(nap_msec)
-
-def saywhat(text):
- stdscr.move(curses.LINES - 1, 0)
- stdscr.clrtoeol()
- stdscr.addstr(text)
-
-def mkpanel(color, rows, cols, tly, tlx):
- win = curses.newwin(rows, cols, tly, tlx)
- pan = panel.new_panel(win)
- if curses.has_colors():
- if color == curses.COLOR_BLUE:
- fg = curses.COLOR_WHITE
- else:
- fg = curses.COLOR_BLACK
- bg = color
- curses.init_pair(color, fg, bg)
- win.bkgdset(ord(' '), curses.color_pair(color))
- else:
- win.bkgdset(ord(' '), curses.A_BOLD)
-
- return pan
-
-def pflush():
- panel.update_panels()
- curses.doupdate()
-
-def fill_panel(pan):
- win = pan.window()
- num = pan.userptr()[1]
-
- win.move(1, 1)
- win.addstr("-pan%c-" % num)
- win.clrtoeol()
- win.box()
-
- maxy, maxx = win.getmaxyx()
- for y in range(2, maxy - 1):
- for x in range(1, maxx - 1):
- win.move(y, x)
- win.addch(num)
-
-def demo_panels(win):
- global stdscr, nap_msec, mod
- stdscr = win
- nap_msec = 1
- mod = ["test", "TEST", "(**)", "*()*", "<-->", "LAST"]
-
- stdscr.refresh()
-
- for y in range(0, curses.LINES - 1):
- for x in range(0, curses.COLS):
- stdscr.addstr("%d" % ((y + x) % 10))
- for y in range(0, 1):
- p1 = mkpanel(curses.COLOR_RED,
- curses.LINES // 2 - 2,
- curses.COLS // 8 + 1,
- 0,
- 0)
- p1.set_userptr("p1")
-
- p2 = mkpanel(curses.COLOR_GREEN,
- curses.LINES // 2 + 1,
- curses.COLS // 7,
- curses.LINES // 4,
- curses.COLS // 10)
- p2.set_userptr("p2")
-
- p3 = mkpanel(curses.COLOR_YELLOW,
- curses.LINES // 4,
- curses.COLS // 10,
- curses.LINES // 2,
- curses.COLS // 9)
- p3.set_userptr("p3")
-
- p4 = mkpanel(curses.COLOR_BLUE,
- curses.LINES // 2 - 2,
- curses.COLS // 8,
- curses.LINES // 2 - 2,
- curses.COLS // 3)
- p4.set_userptr("p4")
-
- p5 = mkpanel(curses.COLOR_MAGENTA,
- curses.LINES // 2 - 2,
- curses.COLS // 8,
- curses.LINES // 2,
- curses.COLS // 2 - 2)
- p5.set_userptr("p5")
-
- fill_panel(p1)
- fill_panel(p2)
- fill_panel(p3)
- fill_panel(p4)
- fill_panel(p5)
- p4.hide()
- p5.hide()
- pflush()
- saywhat("press any key to continue")
- wait_a_while()
-
- saywhat("h3 s1 s2 s4 s5;press any key to continue")
- p1.move(0, 0)
- p3.hide()
- p1.show()
- p2.show()
- p4.show()
- p5.show()
- pflush()
- wait_a_while()
-
- saywhat("s1; press any key to continue")
- p1.show()
- pflush()
- wait_a_while()
-
- saywhat("s2; press any key to continue")
- p2.show()
- pflush()
- wait_a_while()
-
- saywhat("m2; press any key to continue")
- p2.move(curses.LINES // 3 + 1, curses.COLS // 8)
- pflush()
- wait_a_while()
-
- saywhat("s3; press any key to continue")
- p3.show()
- pflush()
- wait_a_while()
-
- saywhat("m3; press any key to continue")
- p3.move(curses.LINES // 4 + 1, curses.COLS // 15)
- pflush()
- wait_a_while()
-
- saywhat("b3; press any key to continue")
- p3.bottom()
- pflush()
- wait_a_while()
-
- saywhat("s4; press any key to continue")
- p4.show()
- pflush()
- wait_a_while()
-
- saywhat("s5; press any key to continue")
- p5.show()
- pflush()
- wait_a_while()
-
- saywhat("t3; press any key to continue")
- p3.top()
- pflush()
- wait_a_while()
-
- saywhat("t1; press any key to continue")
- p1.show()
- pflush()
- wait_a_while()
-
- saywhat("t2; press any key to continue")
- p2.show()
- pflush()
- wait_a_while()
-
- saywhat("t3; press any key to continue")
- p3.show()
- pflush()
- wait_a_while()
-
- saywhat("t4; press any key to continue")
- p4.show()
- pflush()
- wait_a_while()
-
- for itmp in range(0, 6):
- w4 = p4.window()
- w5 = p5.window()
-
- saywhat("m4; press any key to continue")
- w4.move(curses.LINES // 8, 1)
- w4.addstr(mod[itmp])
- p4.move(curses.LINES // 6, itmp * curses.COLS // 8)
- w5.move(curses.LINES // 6, 1)
- w5.addstr(mod[itmp])
- pflush()
- wait_a_while()
-
- saywhat("m5; press any key to continue")
- w4.move(curses.LINES // 6, 1)
- w4.addstr(mod[itmp])
- p5.move(curses.LINES // 3 - 1, itmp * 10 + 6)
- w5.move(curses.LINES // 8, 1)
- w5.addstr(mod[itmp])
- pflush()
- wait_a_while()
-
- saywhat("m4; press any key to continue")
- p4.move(curses.LINES // 6, (itmp + 1) * curses.COLS // 8)
- pflush()
- wait_a_while()
-
- saywhat("t5; press any key to continue")
- p5.top()
- pflush()
- wait_a_while()
-
- saywhat("t2; press any key to continue")
- p2.top()
- pflush()
- wait_a_while()
-
- saywhat("t1; press any key to continue")
- p1.top()
- pflush()
- wait_a_while()
-
- saywhat("d2; press any key to continue")
- del p2
- pflush()
- wait_a_while()
-
- saywhat("h3; press any key to continue")
- p3.hide()
- pflush()
- wait_a_while()
-
- saywhat("d1; press any key to continue")
- del p1
- pflush()
- wait_a_while()
-
- saywhat("d4; press any key to continue")
- del p4
- pflush()
- wait_a_while()
-
- saywhat("d5; press any key to continue")
- del p5
- pflush()
- wait_a_while()
- if nap_msec == 1:
- break
- nap_msec = 100
-
-#
-# one fine day there'll be the menu at this place
-#
-curses.wrapper(demo_panels)
Deleted: python/branches/py3k/Demo/curses/rain.py
==============================================================================
--- python/branches/py3k/Demo/curses/rain.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,94 +0,0 @@
-#!/usr/bin/env python3
-#
-# $Id$
-#
-# somebody should probably check the randrange()s...
-
-import curses
-from random import randrange
-
-def next_j(j):
- if j == 0:
- j = 4
- else:
- j -= 1
-
- if curses.has_colors():
- z = randrange(0, 3)
- color = curses.color_pair(z)
- if z:
- color = color | curses.A_BOLD
- stdscr.attrset(color)
-
- return j
-
-def main(win):
- # we know that the first argument from curses.wrapper() is stdscr.
- # Initialize it globally for convenience.
- global stdscr
- stdscr = win
-
- if curses.has_colors():
- bg = curses.COLOR_BLACK
- curses.init_pair(1, curses.COLOR_BLUE, bg)
- curses.init_pair(2, curses.COLOR_CYAN, bg)
-
- curses.nl()
- curses.noecho()
- # XXX curs_set() always returns ERR
- # curses.curs_set(0)
- stdscr.timeout(0)
-
- c = curses.COLS - 4
- r = curses.LINES - 4
- xpos = [0] * c
- ypos = [0] * r
- for j in range(4, -1, -1):
- xpos[j] = randrange(0, c) + 2
- ypos[j] = randrange(0, r) + 2
-
- j = 0
- while True:
- x = randrange(0, c) + 2
- y = randrange(0, r) + 2
-
- stdscr.addch(y, x, ord('.'))
-
- stdscr.addch(ypos[j], xpos[j], ord('o'))
-
- j = next_j(j)
- stdscr.addch(ypos[j], xpos[j], ord('O'))
-
- j = next_j(j)
- stdscr.addch( ypos[j] - 1, xpos[j], ord('-'))
- stdscr.addstr(ypos[j], xpos[j] - 1, "|.|")
- stdscr.addch( ypos[j] + 1, xpos[j], ord('-'))
-
- j = next_j(j)
- stdscr.addch( ypos[j] - 2, xpos[j], ord('-'))
- stdscr.addstr(ypos[j] - 1, xpos[j] - 1, "/ \\")
- stdscr.addstr(ypos[j], xpos[j] - 2, "| O |")
- stdscr.addstr(ypos[j] + 1, xpos[j] - 1, "\\ /")
- stdscr.addch( ypos[j] + 2, xpos[j], ord('-'))
-
- j = next_j(j)
- stdscr.addch( ypos[j] - 2, xpos[j], ord(' '))
- stdscr.addstr(ypos[j] - 1, xpos[j] - 1, " ")
- stdscr.addstr(ypos[j], xpos[j] - 2, " ")
- stdscr.addstr(ypos[j] + 1, xpos[j] - 1, " ")
- stdscr.addch( ypos[j] + 2, xpos[j], ord(' '))
-
- xpos[j] = x
- ypos[j] = y
-
- ch = stdscr.getch()
- if ch == ord('q') or ch == ord('Q'):
- return
- elif ch == ord('s'):
- stdscr.nodelay(0)
- elif ch == ord(' '):
- stdscr.nodelay(1)
-
- curses.napms(50)
-
-curses.wrapper(main)
Deleted: python/branches/py3k/Demo/curses/tclock.py
==============================================================================
--- python/branches/py3k/Demo/curses/tclock.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,147 +0,0 @@
-#!/usr/bin/env python3
-#
-# $Id$
-#
-# From tclock.c, Copyright Howard Jones <ha.jones(a)ic.ac.uk>, September 1994.
-
-from math import *
-import curses, time
-
-ASPECT = 2.2
-
-def sign(_x):
- if _x < 0: return -1
- return 1
-
-def A2XY(angle, radius):
- return (int(round(ASPECT * radius * sin(angle))),
- int(round(radius * cos(angle))))
-
-def plot(x, y, col):
- stdscr.addch(y, x, col)
-
-# draw a diagonal line using Bresenham's algorithm
-def dline(pair, from_x, from_y, x2, y2, ch):
- if curses.has_colors():
- stdscr.attrset(curses.color_pair(pair))
-
- dx = x2 - from_x
- dy = y2 - from_y
-
- ax = abs(dx * 2)
- ay = abs(dy * 2)
-
- sx = sign(dx)
- sy = sign(dy)
-
- x = from_x
- y = from_y
-
- if ax > ay:
- d = ay - ax // 2
-
- while True:
- plot(x, y, ch)
- if x == x2:
- return
-
- if d >= 0:
- y += sy
- d -= ax
- x += sx
- d += ay
- else:
- d = ax - ay // 2
-
- while True:
- plot(x, y, ch)
- if y == y2:
- return
-
- if d >= 0:
- x += sx
- d -= ay
- y += sy
- d += ax
-
-def main(win):
- global stdscr
- stdscr = win
-
- lastbeep = -1
- my_bg = curses.COLOR_BLACK
-
- stdscr.nodelay(1)
- stdscr.timeout(0)
-# curses.curs_set(0)
- if curses.has_colors():
- curses.init_pair(1, curses.COLOR_RED, my_bg)
- curses.init_pair(2, curses.COLOR_MAGENTA, my_bg)
- curses.init_pair(3, curses.COLOR_GREEN, my_bg)
-
- cx = (curses.COLS - 1) // 2
- cy = curses.LINES // 2
- ch = min( cy-1, int(cx // ASPECT) - 1)
- mradius = (3 * ch) // 4
- hradius = ch // 2
- sradius = 5 * ch // 6
-
- for i in range(0, 12):
- sangle = (i + 1) * 2.0 * pi / 12.0
- sdx, sdy = A2XY(sangle, sradius)
-
- stdscr.addstr(cy - sdy, cx + sdx, "%d" % (i + 1))
-
- stdscr.addstr(0, 0,
- "ASCII Clock by Howard Jones <ha.jones(a)ic.ac.uk>, 1994")
-
- sradius = max(sradius-4, 8)
-
- while True:
- curses.napms(1000)
-
- tim = time.time()
- t = time.localtime(tim)
-
- hours = t[3] + t[4] / 60.0
- if hours > 12.0:
- hours -= 12.0
-
- mangle = t[4] * 2 * pi / 60.0
- mdx, mdy = A2XY(mangle, mradius)
-
- hangle = hours * 2 * pi / 12.0
- hdx, hdy = A2XY(hangle, hradius)
-
- sangle = t[5] * 2 * pi / 60.0
- sdx, sdy = A2XY(sangle, sradius)
-
- dline(3, cx, cy, cx + mdx, cy - mdy, ord('#'))
-
- stdscr.attrset(curses.A_REVERSE)
- dline(2, cx, cy, cx + hdx, cy - hdy, ord('.'))
- stdscr.attroff(curses.A_REVERSE)
-
- if curses.has_colors():
- stdscr.attrset(curses.color_pair(1))
-
- plot(cx + sdx, cy - sdy, ord('O'))
-
- if curses.has_colors():
- stdscr.attrset(curses.color_pair(0))
-
- stdscr.addstr(curses.LINES - 2, 0, time.ctime(tim))
- stdscr.refresh()
- if (t[5] % 5) == 0 and t[5] != lastbeep:
- lastbeep = t[5]
- curses.beep()
-
- ch = stdscr.getch()
- if ch == ord('q'):
- return 0
-
- plot(cx + sdx, cy - sdy, ord(' '))
- dline(0, cx, cy, cx + hdx, cy - hdy, ord(' '))
- dline(0, cx, cy, cx + mdx, cy - mdy, ord(' '))
-
-curses.wrapper(main)
Deleted: python/branches/py3k/Demo/curses/xmas.py
==============================================================================
--- python/branches/py3k/Demo/curses/xmas.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,906 +0,0 @@
-# asciixmas
-# December 1989 Larry Bartz Indianapolis, IN
-#
-# $Id$
-#
-# I'm dreaming of an ascii character-based monochrome Christmas,
-# Just like the ones I used to know!
-# Via a full duplex communications channel,
-# At 9600 bits per second,
-# Even though it's kinda slow.
-#
-# I'm dreaming of an ascii character-based monochrome Christmas,
-# With ev'ry C program I write!
-# May your screen be merry and bright!
-# And may all your Christmases be amber or green,
-# (for reduced eyestrain and improved visibility)!
-#
-#
-# Notes on the Python version:
-# I used a couple of `try...except curses.error' to get around some functions
-# returning ERR. The errors come from using wrapping functions to fill
-# windows to the last character cell. The C version doesn't have this problem,
-# it simply ignores any return values.
-#
-
-import curses
-import sys
-
-FROMWHO = "Thomas Gellekum <tg(a)FreeBSD.org>"
-
-def set_color(win, color):
- if curses.has_colors():
- n = color + 1
- curses.init_pair(n, color, my_bg)
- win.attroff(curses.A_COLOR)
- win.attron(curses.color_pair(n))
-
-def unset_color(win):
- if curses.has_colors():
- win.attrset(curses.color_pair(0))
-
-def look_out(msecs):
- curses.napms(msecs)
- if stdscr.getch() != -1:
- curses.beep()
- sys.exit(0)
-
-def boxit():
- for y in range(0, 20):
- stdscr.addch(y, 7, ord('|'))
-
- for x in range(8, 80):
- stdscr.addch(19, x, ord('_'))
-
- for x in range(0, 80):
- stdscr.addch(22, x, ord('_'))
-
- return
-
-def seas():
- stdscr.addch(4, 1, ord('S'))
- stdscr.addch(6, 1, ord('E'))
- stdscr.addch(8, 1, ord('A'))
- stdscr.addch(10, 1, ord('S'))
- stdscr.addch(12, 1, ord('O'))
- stdscr.addch(14, 1, ord('N'))
- stdscr.addch(16, 1, ord("'"))
- stdscr.addch(18, 1, ord('S'))
-
- return
-
-def greet():
- stdscr.addch(3, 5, ord('G'))
- stdscr.addch(5, 5, ord('R'))
- stdscr.addch(7, 5, ord('E'))
- stdscr.addch(9, 5, ord('E'))
- stdscr.addch(11, 5, ord('T'))
- stdscr.addch(13, 5, ord('I'))
- stdscr.addch(15, 5, ord('N'))
- stdscr.addch(17, 5, ord('G'))
- stdscr.addch(19, 5, ord('S'))
-
- return
-
-def fromwho():
- stdscr.addstr(21, 13, FROMWHO)
- return
-
-def tree():
- set_color(treescrn, curses.COLOR_GREEN)
- treescrn.addch(1, 11, ord('/'))
- treescrn.addch(2, 11, ord('/'))
- treescrn.addch(3, 10, ord('/'))
- treescrn.addch(4, 9, ord('/'))
- treescrn.addch(5, 9, ord('/'))
- treescrn.addch(6, 8, ord('/'))
- treescrn.addch(7, 7, ord('/'))
- treescrn.addch(8, 6, ord('/'))
- treescrn.addch(9, 6, ord('/'))
- treescrn.addch(10, 5, ord('/'))
- treescrn.addch(11, 3, ord('/'))
- treescrn.addch(12, 2, ord('/'))
-
- treescrn.addch(1, 13, ord('\\'))
- treescrn.addch(2, 13, ord('\\'))
- treescrn.addch(3, 14, ord('\\'))
- treescrn.addch(4, 15, ord('\\'))
- treescrn.addch(5, 15, ord('\\'))
- treescrn.addch(6, 16, ord('\\'))
- treescrn.addch(7, 17, ord('\\'))
- treescrn.addch(8, 18, ord('\\'))
- treescrn.addch(9, 18, ord('\\'))
- treescrn.addch(10, 19, ord('\\'))
- treescrn.addch(11, 21, ord('\\'))
- treescrn.addch(12, 22, ord('\\'))
-
- treescrn.addch(4, 10, ord('_'))
- treescrn.addch(4, 14, ord('_'))
- treescrn.addch(8, 7, ord('_'))
- treescrn.addch(8, 17, ord('_'))
-
- treescrn.addstr(13, 0, "//////////// \\\\\\\\\\\\\\\\\\\\\\\\")
-
- treescrn.addstr(14, 11, "| |")
- treescrn.addstr(15, 11, "|_|")
-
- unset_color(treescrn)
- treescrn.refresh()
- w_del_msg.refresh()
-
- return
-
-def balls():
- treescrn.overlay(treescrn2)
-
- set_color(treescrn2, curses.COLOR_BLUE)
- treescrn2.addch(3, 9, ord('@'))
- treescrn2.addch(3, 15, ord('@'))
- treescrn2.addch(4, 8, ord('@'))
- treescrn2.addch(4, 16, ord('@'))
- treescrn2.addch(5, 7, ord('@'))
- treescrn2.addch(5, 17, ord('@'))
- treescrn2.addch(7, 6, ord('@'))
- treescrn2.addch(7, 18, ord('@'))
- treescrn2.addch(8, 5, ord('@'))
- treescrn2.addch(8, 19, ord('@'))
- treescrn2.addch(10, 4, ord('@'))
- treescrn2.addch(10, 20, ord('@'))
- treescrn2.addch(11, 2, ord('@'))
- treescrn2.addch(11, 22, ord('@'))
- treescrn2.addch(12, 1, ord('@'))
- treescrn2.addch(12, 23, ord('@'))
-
- unset_color(treescrn2)
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def star():
- treescrn2.attrset(curses.A_BOLD | curses.A_BLINK)
- set_color(treescrn2, curses.COLOR_YELLOW)
-
- treescrn2.addch(0, 12, ord('*'))
- treescrn2.standend()
-
- unset_color(treescrn2)
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def strng1():
- treescrn2.attrset(curses.A_BOLD | curses.A_BLINK)
- set_color(treescrn2, curses.COLOR_WHITE)
-
- treescrn2.addch(3, 13, ord('\''))
- treescrn2.addch(3, 12, ord(':'))
- treescrn2.addch(3, 11, ord('.'))
-
- treescrn2.attroff(curses.A_BOLD | curses.A_BLINK)
- unset_color(treescrn2)
-
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def strng2():
- treescrn2.attrset(curses.A_BOLD | curses.A_BLINK)
- set_color(treescrn2, curses.COLOR_WHITE)
-
- treescrn2.addch(5, 14, ord('\''))
- treescrn2.addch(5, 13, ord(':'))
- treescrn2.addch(5, 12, ord('.'))
- treescrn2.addch(5, 11, ord(','))
- treescrn2.addch(6, 10, ord('\''))
- treescrn2.addch(6, 9, ord(':'))
-
- treescrn2.attroff(curses.A_BOLD | curses.A_BLINK)
- unset_color(treescrn2)
-
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def strng3():
- treescrn2.attrset(curses.A_BOLD | curses.A_BLINK)
- set_color(treescrn2, curses.COLOR_WHITE)
-
- treescrn2.addch(7, 16, ord('\''))
- treescrn2.addch(7, 15, ord(':'))
- treescrn2.addch(7, 14, ord('.'))
- treescrn2.addch(7, 13, ord(','))
- treescrn2.addch(8, 12, ord('\''))
- treescrn2.addch(8, 11, ord(':'))
- treescrn2.addch(8, 10, ord('.'))
- treescrn2.addch(8, 9, ord(','))
-
- treescrn2.attroff(curses.A_BOLD | curses.A_BLINK)
- unset_color(treescrn2)
-
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def strng4():
- treescrn2.attrset(curses.A_BOLD | curses.A_BLINK)
- set_color(treescrn2, curses.COLOR_WHITE)
-
- treescrn2.addch(9, 17, ord('\''))
- treescrn2.addch(9, 16, ord(':'))
- treescrn2.addch(9, 15, ord('.'))
- treescrn2.addch(9, 14, ord(','))
- treescrn2.addch(10, 13, ord('\''))
- treescrn2.addch(10, 12, ord(':'))
- treescrn2.addch(10, 11, ord('.'))
- treescrn2.addch(10, 10, ord(','))
- treescrn2.addch(11, 9, ord('\''))
- treescrn2.addch(11, 8, ord(':'))
- treescrn2.addch(11, 7, ord('.'))
- treescrn2.addch(11, 6, ord(','))
- treescrn2.addch(12, 5, ord('\''))
-
- treescrn2.attroff(curses.A_BOLD | curses.A_BLINK)
- unset_color(treescrn2)
-
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def strng5():
- treescrn2.attrset(curses.A_BOLD | curses.A_BLINK)
- set_color(treescrn2, curses.COLOR_WHITE)
-
- treescrn2.addch(11, 19, ord('\''))
- treescrn2.addch(11, 18, ord(':'))
- treescrn2.addch(11, 17, ord('.'))
- treescrn2.addch(11, 16, ord(','))
- treescrn2.addch(12, 15, ord('\''))
- treescrn2.addch(12, 14, ord(':'))
- treescrn2.addch(12, 13, ord('.'))
- treescrn2.addch(12, 12, ord(','))
-
- treescrn2.attroff(curses.A_BOLD | curses.A_BLINK)
- unset_color(treescrn2)
-
- # save a fully lit tree
- treescrn2.overlay(treescrn)
-
- treescrn2.refresh()
- w_del_msg.refresh()
- return
-
-def blinkit():
- treescrn8.touchwin()
-
- for cycle in range(5):
- if cycle == 0:
- treescrn3.overlay(treescrn8)
- treescrn8.refresh()
- w_del_msg.refresh()
- break
- elif cycle == 1:
- treescrn4.overlay(treescrn8)
- treescrn8.refresh()
- w_del_msg.refresh()
- break
- elif cycle == 2:
- treescrn5.overlay(treescrn8)
- treescrn8.refresh()
- w_del_msg.refresh()
- break
- elif cycle == 3:
- treescrn6.overlay(treescrn8)
- treescrn8.refresh()
- w_del_msg.refresh()
- break
- elif cycle == 4:
- treescrn7.overlay(treescrn8)
- treescrn8.refresh()
- w_del_msg.refresh()
- break
-
- treescrn8.touchwin()
-
- # ALL ON
- treescrn.overlay(treescrn8)
- treescrn8.refresh()
- w_del_msg.refresh()
-
- return
-
-def deer_step(win, y, x):
- win.mvwin(y, x)
- win.refresh()
- w_del_msg.refresh()
- look_out(5)
-
-def reindeer():
- y_pos = 0
-
- for x_pos in range(70, 62, -1):
- if x_pos < 66: y_pos = 1
- for looper in range(0, 4):
- dotdeer0.addch(y_pos, x_pos, ord('.'))
- dotdeer0.refresh()
- w_del_msg.refresh()
- dotdeer0.erase()
- dotdeer0.refresh()
- w_del_msg.refresh()
- look_out(50)
-
- y_pos = 2
-
- for x_pos in range(x_pos - 1, 50, -1):
- for looper in range(0, 4):
- if x_pos < 56:
- y_pos = 3
-
- try:
- stardeer0.addch(y_pos, x_pos, ord('*'))
- except curses.error:
- pass
- stardeer0.refresh()
- w_del_msg.refresh()
- stardeer0.erase()
- stardeer0.refresh()
- w_del_msg.refresh()
- else:
- dotdeer0.addch(y_pos, x_pos, ord('*'))
- dotdeer0.refresh()
- w_del_msg.refresh()
- dotdeer0.erase()
- dotdeer0.refresh()
- w_del_msg.refresh()
-
- x_pos = 58
-
- for y_pos in range(2, 5):
- lildeer0.touchwin()
- lildeer0.refresh()
- w_del_msg.refresh()
-
- for looper in range(0, 4):
- deer_step(lildeer3, y_pos, x_pos)
- deer_step(lildeer2, y_pos, x_pos)
- deer_step(lildeer1, y_pos, x_pos)
- deer_step(lildeer2, y_pos, x_pos)
- deer_step(lildeer3, y_pos, x_pos)
-
- lildeer0.touchwin()
- lildeer0.refresh()
- w_del_msg.refresh()
-
- x_pos -= 2
-
- x_pos = 35
-
- for y_pos in range(5, 10):
-
- middeer0.touchwin()
- middeer0.refresh()
- w_del_msg.refresh()
-
- for looper in range(2):
- deer_step(middeer3, y_pos, x_pos)
- deer_step(middeer2, y_pos, x_pos)
- deer_step(middeer1, y_pos, x_pos)
- deer_step(middeer2, y_pos, x_pos)
- deer_step(middeer3, y_pos, x_pos)
-
- middeer0.touchwin()
- middeer0.refresh()
- w_del_msg.refresh()
-
- x_pos -= 3
-
- look_out(300)
-
- y_pos = 1
-
- for x_pos in range(8, 16):
- deer_step(bigdeer4, y_pos, x_pos)
- deer_step(bigdeer3, y_pos, x_pos)
- deer_step(bigdeer2, y_pos, x_pos)
- deer_step(bigdeer1, y_pos, x_pos)
- deer_step(bigdeer2, y_pos, x_pos)
- deer_step(bigdeer3, y_pos, x_pos)
- deer_step(bigdeer4, y_pos, x_pos)
- deer_step(bigdeer0, y_pos, x_pos)
-
- x_pos -= 1
-
- for looper in range(0, 6):
- deer_step(lookdeer4, y_pos, x_pos)
- deer_step(lookdeer3, y_pos, x_pos)
- deer_step(lookdeer2, y_pos, x_pos)
- deer_step(lookdeer1, y_pos, x_pos)
- deer_step(lookdeer2, y_pos, x_pos)
- deer_step(lookdeer3, y_pos, x_pos)
- deer_step(lookdeer4, y_pos, x_pos)
-
- deer_step(lookdeer0, y_pos, x_pos)
-
- for y_pos in range(y_pos, 10):
- for looper in range(0, 2):
- deer_step(bigdeer4, y_pos, x_pos)
- deer_step(bigdeer3, y_pos, x_pos)
- deer_step(bigdeer2, y_pos, x_pos)
- deer_step(bigdeer1, y_pos, x_pos)
- deer_step(bigdeer2, y_pos, x_pos)
- deer_step(bigdeer3, y_pos, x_pos)
- deer_step(bigdeer4, y_pos, x_pos)
- deer_step(bigdeer0, y_pos, x_pos)
-
- y_pos -= 1
-
- deer_step(lookdeer3, y_pos, x_pos)
- return
-
-def main(win):
- global stdscr
- stdscr = win
-
- global my_bg, y_pos, x_pos
- global treescrn, treescrn2, treescrn3, treescrn4
- global treescrn5, treescrn6, treescrn7, treescrn8
- global dotdeer0, stardeer0
- global lildeer0, lildeer1, lildeer2, lildeer3
- global middeer0, middeer1, middeer2, middeer3
- global bigdeer0, bigdeer1, bigdeer2, bigdeer3, bigdeer4
- global lookdeer0, lookdeer1, lookdeer2, lookdeer3, lookdeer4
- global w_holiday, w_del_msg
-
- my_bg = curses.COLOR_BLACK
- # curses.curs_set(0)
-
- treescrn = curses.newwin(16, 27, 3, 53)
- treescrn2 = curses.newwin(16, 27, 3, 53)
- treescrn3 = curses.newwin(16, 27, 3, 53)
- treescrn4 = curses.newwin(16, 27, 3, 53)
- treescrn5 = curses.newwin(16, 27, 3, 53)
- treescrn6 = curses.newwin(16, 27, 3, 53)
- treescrn7 = curses.newwin(16, 27, 3, 53)
- treescrn8 = curses.newwin(16, 27, 3, 53)
-
- dotdeer0 = curses.newwin(3, 71, 0, 8)
-
- stardeer0 = curses.newwin(4, 56, 0, 8)
-
- lildeer0 = curses.newwin(7, 53, 0, 8)
- lildeer1 = curses.newwin(2, 4, 0, 0)
- lildeer2 = curses.newwin(2, 4, 0, 0)
- lildeer3 = curses.newwin(2, 4, 0, 0)
-
- middeer0 = curses.newwin(15, 42, 0, 8)
- middeer1 = curses.newwin(3, 7, 0, 0)
- middeer2 = curses.newwin(3, 7, 0, 0)
- middeer3 = curses.newwin(3, 7, 0, 0)
-
- bigdeer0 = curses.newwin(10, 23, 0, 0)
- bigdeer1 = curses.newwin(10, 23, 0, 0)
- bigdeer2 = curses.newwin(10, 23, 0, 0)
- bigdeer3 = curses.newwin(10, 23, 0, 0)
- bigdeer4 = curses.newwin(10, 23, 0, 0)
-
- lookdeer0 = curses.newwin(10, 25, 0, 0)
- lookdeer1 = curses.newwin(10, 25, 0, 0)
- lookdeer2 = curses.newwin(10, 25, 0, 0)
- lookdeer3 = curses.newwin(10, 25, 0, 0)
- lookdeer4 = curses.newwin(10, 25, 0, 0)
-
- w_holiday = curses.newwin(1, 27, 3, 27)
-
- w_del_msg = curses.newwin(1, 20, 23, 60)
-
- try:
- w_del_msg.addstr(0, 0, "Hit any key to quit")
- except curses.error:
- pass
-
- try:
- w_holiday.addstr(0, 0, "H A P P Y H O L I D A Y S")
- except curses.error:
- pass
-
- # set up the windows for our various reindeer
- lildeer1.addch(0, 0, ord('V'))
- lildeer1.addch(1, 0, ord('@'))
- lildeer1.addch(1, 1, ord('<'))
- lildeer1.addch(1, 2, ord('>'))
- try:
- lildeer1.addch(1, 3, ord('~'))
- except curses.error:
- pass
-
- lildeer2.addch(0, 0, ord('V'))
- lildeer2.addch(1, 0, ord('@'))
- lildeer2.addch(1, 1, ord('|'))
- lildeer2.addch(1, 2, ord('|'))
- try:
- lildeer2.addch(1, 3, ord('~'))
- except curses.error:
- pass
-
- lildeer3.addch(0, 0, ord('V'))
- lildeer3.addch(1, 0, ord('@'))
- lildeer3.addch(1, 1, ord('>'))
- lildeer3.addch(1, 2, ord('<'))
- try:
- lildeer2.addch(1, 3, ord('~')) # XXX
- except curses.error:
- pass
-
- middeer1.addch(0, 2, ord('y'))
- middeer1.addch(0, 3, ord('y'))
- middeer1.addch(1, 2, ord('0'))
- middeer1.addch(1, 3, ord('('))
- middeer1.addch(1, 4, ord('='))
- middeer1.addch(1, 5, ord(')'))
- middeer1.addch(1, 6, ord('~'))
- middeer1.addch(2, 3, ord('\\'))
- middeer1.addch(2, 5, ord('/'))
-
- middeer2.addch(0, 2, ord('y'))
- middeer2.addch(0, 3, ord('y'))
- middeer2.addch(1, 2, ord('0'))
- middeer2.addch(1, 3, ord('('))
- middeer2.addch(1, 4, ord('='))
- middeer2.addch(1, 5, ord(')'))
- middeer2.addch(1, 6, ord('~'))
- middeer2.addch(2, 3, ord('|'))
- middeer2.addch(2, 5, ord('|'))
-
- middeer3.addch(0, 2, ord('y'))
- middeer3.addch(0, 3, ord('y'))
- middeer3.addch(1, 2, ord('0'))
- middeer3.addch(1, 3, ord('('))
- middeer3.addch(1, 4, ord('='))
- middeer3.addch(1, 5, ord(')'))
- middeer3.addch(1, 6, ord('~'))
- middeer3.addch(2, 3, ord('/'))
- middeer3.addch(2, 5, ord('\\'))
-
- bigdeer1.addch(0, 17, ord('\\'))
- bigdeer1.addch(0, 18, ord('/'))
- bigdeer1.addch(0, 19, ord('\\'))
- bigdeer1.addch(0, 20, ord('/'))
- bigdeer1.addch(1, 18, ord('\\'))
- bigdeer1.addch(1, 20, ord('/'))
- bigdeer1.addch(2, 19, ord('|'))
- bigdeer1.addch(2, 20, ord('_'))
- bigdeer1.addch(3, 18, ord('/'))
- bigdeer1.addch(3, 19, ord('^'))
- bigdeer1.addch(3, 20, ord('0'))
- bigdeer1.addch(3, 21, ord('\\'))
- bigdeer1.addch(4, 17, ord('/'))
- bigdeer1.addch(4, 18, ord('/'))
- bigdeer1.addch(4, 19, ord('\\'))
- bigdeer1.addch(4, 22, ord('\\'))
- bigdeer1.addstr(5, 7, "^~~~~~~~~// ~~U")
- bigdeer1.addstr(6, 7, "( \\_____( /") # ))
- bigdeer1.addstr(7, 8, "( ) /")
- bigdeer1.addstr(8, 9, "\\\\ /")
- bigdeer1.addstr(9, 11, "\\>/>")
-
- bigdeer2.addch(0, 17, ord('\\'))
- bigdeer2.addch(0, 18, ord('/'))
- bigdeer2.addch(0, 19, ord('\\'))
- bigdeer2.addch(0, 20, ord('/'))
- bigdeer2.addch(1, 18, ord('\\'))
- bigdeer2.addch(1, 20, ord('/'))
- bigdeer2.addch(2, 19, ord('|'))
- bigdeer2.addch(2, 20, ord('_'))
- bigdeer2.addch(3, 18, ord('/'))
- bigdeer2.addch(3, 19, ord('^'))
- bigdeer2.addch(3, 20, ord('0'))
- bigdeer2.addch(3, 21, ord('\\'))
- bigdeer2.addch(4, 17, ord('/'))
- bigdeer2.addch(4, 18, ord('/'))
- bigdeer2.addch(4, 19, ord('\\'))
- bigdeer2.addch(4, 22, ord('\\'))
- bigdeer2.addstr(5, 7, "^~~~~~~~~// ~~U")
- bigdeer2.addstr(6, 7, "(( )____( /") # ))
- bigdeer2.addstr(7, 7, "( / |")
- bigdeer2.addstr(8, 8, "\\/ |")
- bigdeer2.addstr(9, 9, "|> |>")
-
- bigdeer3.addch(0, 17, ord('\\'))
- bigdeer3.addch(0, 18, ord('/'))
- bigdeer3.addch(0, 19, ord('\\'))
- bigdeer3.addch(0, 20, ord('/'))
- bigdeer3.addch(1, 18, ord('\\'))
- bigdeer3.addch(1, 20, ord('/'))
- bigdeer3.addch(2, 19, ord('|'))
- bigdeer3.addch(2, 20, ord('_'))
- bigdeer3.addch(3, 18, ord('/'))
- bigdeer3.addch(3, 19, ord('^'))
- bigdeer3.addch(3, 20, ord('0'))
- bigdeer3.addch(3, 21, ord('\\'))
- bigdeer3.addch(4, 17, ord('/'))
- bigdeer3.addch(4, 18, ord('/'))
- bigdeer3.addch(4, 19, ord('\\'))
- bigdeer3.addch(4, 22, ord('\\'))
- bigdeer3.addstr(5, 7, "^~~~~~~~~// ~~U")
- bigdeer3.addstr(6, 6, "( ()_____( /") # ))
- bigdeer3.addstr(7, 6, "/ / /")
- bigdeer3.addstr(8, 5, "|/ \\")
- bigdeer3.addstr(9, 5, "/> \\>")
-
- bigdeer4.addch(0, 17, ord('\\'))
- bigdeer4.addch(0, 18, ord('/'))
- bigdeer4.addch(0, 19, ord('\\'))
- bigdeer4.addch(0, 20, ord('/'))
- bigdeer4.addch(1, 18, ord('\\'))
- bigdeer4.addch(1, 20, ord('/'))
- bigdeer4.addch(2, 19, ord('|'))
- bigdeer4.addch(2, 20, ord('_'))
- bigdeer4.addch(3, 18, ord('/'))
- bigdeer4.addch(3, 19, ord('^'))
- bigdeer4.addch(3, 20, ord('0'))
- bigdeer4.addch(3, 21, ord('\\'))
- bigdeer4.addch(4, 17, ord('/'))
- bigdeer4.addch(4, 18, ord('/'))
- bigdeer4.addch(4, 19, ord('\\'))
- bigdeer4.addch(4, 22, ord('\\'))
- bigdeer4.addstr(5, 7, "^~~~~~~~~// ~~U")
- bigdeer4.addstr(6, 6, "( )______( /") # )
- bigdeer4.addstr(7, 5, "(/ \\") # )
- bigdeer4.addstr(8, 0, "v___= ----^")
-
- lookdeer1.addstr(0, 16, "\\/ \\/")
- lookdeer1.addstr(1, 17, "\\Y/ \\Y/")
- lookdeer1.addstr(2, 19, "\\=/")
- lookdeer1.addstr(3, 17, "^\\o o/^")
- lookdeer1.addstr(4, 17, "//( )")
- lookdeer1.addstr(5, 7, "^~~~~~~~~// \\O/")
- lookdeer1.addstr(6, 7, "( \\_____( /") # ))
- lookdeer1.addstr(7, 8, "( ) /")
- lookdeer1.addstr(8, 9, "\\\\ /")
- lookdeer1.addstr(9, 11, "\\>/>")
-
- lookdeer2.addstr(0, 16, "\\/ \\/")
- lookdeer2.addstr(1, 17, "\\Y/ \\Y/")
- lookdeer2.addstr(2, 19, "\\=/")
- lookdeer2.addstr(3, 17, "^\\o o/^")
- lookdeer2.addstr(4, 17, "//( )")
- lookdeer2.addstr(5, 7, "^~~~~~~~~// \\O/")
- lookdeer2.addstr(6, 7, "(( )____( /") # ))
- lookdeer2.addstr(7, 7, "( / |")
- lookdeer2.addstr(8, 8, "\\/ |")
- lookdeer2.addstr(9, 9, "|> |>")
-
- lookdeer3.addstr(0, 16, "\\/ \\/")
- lookdeer3.addstr(1, 17, "\\Y/ \\Y/")
- lookdeer3.addstr(2, 19, "\\=/")
- lookdeer3.addstr(3, 17, "^\\o o/^")
- lookdeer3.addstr(4, 17, "//( )")
- lookdeer3.addstr(5, 7, "^~~~~~~~~// \\O/")
- lookdeer3.addstr(6, 6, "( ()_____( /") # ))
- lookdeer3.addstr(7, 6, "/ / /")
- lookdeer3.addstr(8, 5, "|/ \\")
- lookdeer3.addstr(9, 5, "/> \\>")
-
- lookdeer4.addstr(0, 16, "\\/ \\/")
- lookdeer4.addstr(1, 17, "\\Y/ \\Y/")
- lookdeer4.addstr(2, 19, "\\=/")
- lookdeer4.addstr(3, 17, "^\\o o/^")
- lookdeer4.addstr(4, 17, "//( )")
- lookdeer4.addstr(5, 7, "^~~~~~~~~// \\O/")
- lookdeer4.addstr(6, 6, "( )______( /") # )
- lookdeer4.addstr(7, 5, "(/ \\") # )
- lookdeer4.addstr(8, 0, "v___= ----^")
-
- ###############################################
- curses.cbreak()
- stdscr.nodelay(1)
-
- while 1:
- stdscr.clear()
- treescrn.erase()
- w_del_msg.touchwin()
- treescrn.touchwin()
- treescrn2.erase()
- treescrn2.touchwin()
- treescrn8.erase()
- treescrn8.touchwin()
- stdscr.refresh()
- look_out(150)
- boxit()
- stdscr.refresh()
- look_out(150)
- seas()
- stdscr.refresh()
- greet()
- stdscr.refresh()
- look_out(150)
- fromwho()
- stdscr.refresh()
- look_out(150)
- tree()
- look_out(150)
- balls()
- look_out(150)
- star()
- look_out(150)
- strng1()
- strng2()
- strng3()
- strng4()
- strng5()
-
- # set up the windows for our blinking trees
- #
- # treescrn3
- treescrn.overlay(treescrn3)
-
- # balls
- treescrn3.addch(4, 18, ord(' '))
- treescrn3.addch(7, 6, ord(' '))
- treescrn3.addch(8, 19, ord(' '))
- treescrn3.addch(11, 22, ord(' '))
-
- # star
- treescrn3.addch(0, 12, ord('*'))
-
- # strng1
- treescrn3.addch(3, 11, ord(' '))
-
- # strng2
- treescrn3.addch(5, 13, ord(' '))
- treescrn3.addch(6, 10, ord(' '))
-
- # strng3
- treescrn3.addch(7, 16, ord(' '))
- treescrn3.addch(7, 14, ord(' '))
-
- # strng4
- treescrn3.addch(10, 13, ord(' '))
- treescrn3.addch(10, 10, ord(' '))
- treescrn3.addch(11, 8, ord(' '))
-
- # strng5
- treescrn3.addch(11, 18, ord(' '))
- treescrn3.addch(12, 13, ord(' '))
-
- # treescrn4
- treescrn.overlay(treescrn4)
-
- # balls
- treescrn4.addch(3, 9, ord(' '))
- treescrn4.addch(4, 16, ord(' '))
- treescrn4.addch(7, 6, ord(' '))
- treescrn4.addch(8, 19, ord(' '))
- treescrn4.addch(11, 2, ord(' '))
- treescrn4.addch(12, 23, ord(' '))
-
- # star
- treescrn4.standout()
- treescrn4.addch(0, 12, ord('*'))
- treescrn4.standend()
-
- # strng1
- treescrn4.addch(3, 13, ord(' '))
-
- # strng2
-
- # strng3
- treescrn4.addch(7, 15, ord(' '))
- treescrn4.addch(8, 11, ord(' '))
-
- # strng4
- treescrn4.addch(9, 16, ord(' '))
- treescrn4.addch(10, 12, ord(' '))
- treescrn4.addch(11, 8, ord(' '))
-
- # strng5
- treescrn4.addch(11, 18, ord(' '))
- treescrn4.addch(12, 14, ord(' '))
-
- # treescrn5
- treescrn.overlay(treescrn5)
-
- # balls
- treescrn5.addch(3, 15, ord(' '))
- treescrn5.addch(10, 20, ord(' '))
- treescrn5.addch(12, 1, ord(' '))
-
- # star
- treescrn5.addch(0, 12, ord(' '))
-
- # strng1
- treescrn5.addch(3, 11, ord(' '))
-
- # strng2
- treescrn5.addch(5, 12, ord(' '))
-
- # strng3
- treescrn5.addch(7, 14, ord(' '))
- treescrn5.addch(8, 10, ord(' '))
-
- # strng4
- treescrn5.addch(9, 15, ord(' '))
- treescrn5.addch(10, 11, ord(' '))
- treescrn5.addch(11, 7, ord(' '))
-
- # strng5
- treescrn5.addch(11, 17, ord(' '))
- treescrn5.addch(12, 13, ord(' '))
-
- # treescrn6
- treescrn.overlay(treescrn6)
-
- # balls
- treescrn6.addch(6, 7, ord(' '))
- treescrn6.addch(7, 18, ord(' '))
- treescrn6.addch(10, 4, ord(' '))
- treescrn6.addch(11, 23, ord(' '))
-
- # star
- treescrn6.standout()
- treescrn6.addch(0, 12, ord('*'))
- treescrn6.standend()
-
- # strng1
-
- # strng2
- treescrn6.addch(5, 11, ord(' '))
-
- # strng3
- treescrn6.addch(7, 13, ord(' '))
- treescrn6.addch(8, 9, ord(' '))
-
- # strng4
- treescrn6.addch(9, 14, ord(' '))
- treescrn6.addch(10, 10, ord(' '))
- treescrn6.addch(11, 6, ord(' '))
-
- # strng5
- treescrn6.addch(11, 16, ord(' '))
- treescrn6.addch(12, 12, ord(' '))
-
- # treescrn7
-
- treescrn.overlay(treescrn7)
-
- # balls
- treescrn7.addch(3, 15, ord(' '))
- treescrn7.addch(6, 7, ord(' '))
- treescrn7.addch(7, 18, ord(' '))
- treescrn7.addch(10, 4, ord(' '))
- treescrn7.addch(11, 22, ord(' '))
-
- # star
- treescrn7.addch(0, 12, ord('*'))
-
- # strng1
- treescrn7.addch(3, 12, ord(' '))
-
- # strng2
- treescrn7.addch(5, 13, ord(' '))
- treescrn7.addch(6, 9, ord(' '))
-
- # strng3
- treescrn7.addch(7, 15, ord(' '))
- treescrn7.addch(8, 11, ord(' '))
-
- # strng4
- treescrn7.addch(9, 16, ord(' '))
- treescrn7.addch(10, 12, ord(' '))
- treescrn7.addch(11, 8, ord(' '))
-
- # strng5
- treescrn7.addch(11, 18, ord(' '))
- treescrn7.addch(12, 14, ord(' '))
-
- look_out(150)
- reindeer()
-
- w_holiday.touchwin()
- w_holiday.refresh()
- w_del_msg.refresh()
-
- look_out(500)
- for i in range(0, 20):
- blinkit()
-
-curses.wrapper(main)
Deleted: python/branches/py3k/Demo/scripts/eqfix.py
==============================================================================
--- python/branches/py3k/Demo/scripts/eqfix.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,198 +0,0 @@
-#! /usr/bin/env python3
-
-# Fix Python source files to use the new equality test operator, i.e.,
-# if x = y: ...
-# is changed to
-# if x == y: ...
-# The script correctly tokenizes the Python program to reliably
-# distinguish between assignments and equality tests.
-#
-# Command line arguments are files or directories to be processed.
-# Directories are searched recursively for files whose name looks
-# like a python module.
-# Symbolic links are always ignored (except as explicit directory
-# arguments). Of course, the original file is kept as a back-up
-# (with a "~" attached to its name).
-# It complains about binaries (files containing null bytes)
-# and about files that are ostensibly not Python files: if the first
-# line starts with '#!' and does not contain the string 'python'.
-#
-# Changes made are reported to stdout in a diff-like format.
-#
-# Undoubtedly you can do this using find and sed or perl, but this is
-# a nice example of Python code that recurses down a directory tree
-# and uses regular expressions. Also note several subtleties like
-# preserving the file's mode and avoiding to even write a temp file
-# when no changes are needed for a file.
-#
-# NB: by changing only the function fixline() you can turn this
-# into a program for a different change to Python programs...
-
-import sys
-import re
-import os
-from stat import *
-import string
-
-err = sys.stderr.write
-dbg = err
-rep = sys.stdout.write
-
-def main():
- bad = 0
- if not sys.argv[1:]: # No arguments
- err('usage: ' + sys.argv[0] + ' file-or-directory ...\n')
- sys.exit(2)
- for arg in sys.argv[1:]:
- if os.path.isdir(arg):
- if recursedown(arg): bad = 1
- elif os.path.islink(arg):
- err(arg + ': will not process symbolic links\n')
- bad = 1
- else:
- if fix(arg): bad = 1
- sys.exit(bad)
-
-ispythonprog = re.compile('^[a-zA-Z0-9_]+\.py$')
-def ispython(name):
- return ispythonprog.match(name) >= 0
-
-def recursedown(dirname):
- dbg('recursedown(%r)\n' % (dirname,))
- bad = 0
- try:
- names = os.listdir(dirname)
- except os.error as msg:
- err('%s: cannot list directory: %r\n' % (dirname, msg))
- return 1
- names.sort()
- subdirs = []
- for name in names:
- if name in (os.curdir, os.pardir): continue
- fullname = os.path.join(dirname, name)
- if os.path.islink(fullname): pass
- elif os.path.isdir(fullname):
- subdirs.append(fullname)
- elif ispython(name):
- if fix(fullname): bad = 1
- for fullname in subdirs:
- if recursedown(fullname): bad = 1
- return bad
-
-def fix(filename):
-## dbg('fix(%r)\n' % (dirname,))
- try:
- f = open(filename, 'r')
- except IOError as msg:
- err('%s: cannot open: %r\n' % (filename, msg))
- return 1
- head, tail = os.path.split(filename)
- tempname = os.path.join(head, '@' + tail)
- g = None
- # If we find a match, we rewind the file and start over but
- # now copy everything to a temp file.
- lineno = 0
- while 1:
- line = f.readline()
- if not line: break
- lineno = lineno + 1
- if g is None and '\0' in line:
- # Check for binary files
- err(filename + ': contains null bytes; not fixed\n')
- f.close()
- return 1
- if lineno == 1 and g is None and line[:2] == '#!':
- # Check for non-Python scripts
- words = string.split(line[2:])
- if words and re.search('[pP]ython', words[0]) < 0:
- msg = filename + ': ' + words[0]
- msg = msg + ' script; not fixed\n'
- err(msg)
- f.close()
- return 1
- while line[-2:] == '\\\n':
- nextline = f.readline()
- if not nextline: break
- line = line + nextline
- lineno = lineno + 1
- newline = fixline(line)
- if newline != line:
- if g is None:
- try:
- g = open(tempname, 'w')
- except IOError as msg:
- f.close()
- err('%s: cannot create: %r\n' % (tempname, msg))
- return 1
- f.seek(0)
- lineno = 0
- rep(filename + ':\n')
- continue # restart from the beginning
- rep(repr(lineno) + '\n')
- rep('< ' + line)
- rep('> ' + newline)
- if g is not None:
- g.write(newline)
-
- # End of file
- f.close()
- if not g: return 0 # No changes
-
- # Finishing touch -- move files
-
- # First copy the file's mode to the temp file
- try:
- statbuf = os.stat(filename)
- os.chmod(tempname, statbuf[ST_MODE] & 0o7777)
- except os.error as msg:
- err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
- # Then make a backup of the original file as filename~
- try:
- os.rename(filename, filename + '~')
- except os.error as msg:
- err('%s: warning: backup failed (%r)\n' % (filename, msg))
- # Now move the temp file to the original file
- try:
- os.rename(tempname, filename)
- except os.error as msg:
- err('%s: rename failed (%r)\n' % (filename, msg))
- return 1
- # Return succes
- return 0
-
-
-from tokenize import tokenprog
-
-match = {'if':':', 'elif':':', 'while':':', 'return':'\n', \
- '(':')', '[':']', '{':'}', '`':'`'}
-
-def fixline(line):
- # Quick check for easy case
- if '=' not in line: return line
-
- i, n = 0, len(line)
- stack = []
- while i < n:
- j = tokenprog.match(line, i)
- if j < 0:
- # A bad token; forget about the rest of this line
- print('(Syntax error:)')
- print(line, end=' ')
- return line
- a, b = tokenprog.regs[3] # Location of the token proper
- token = line[a:b]
- i = i+j
- if stack and token == stack[-1]:
- del stack[-1]
- elif token in match:
- stack.append(match[token])
- elif token == '=' and stack:
- line = line[:a] + '==' + line[b:]
- i, n = a + len('=='), len(line)
- elif token == '==' and not stack:
- print('(Warning: \'==\' at top level:)')
- print(line, end=' ')
- return line
-
-if __name__ == "__main__":
- main()
Deleted: python/branches/py3k/Demo/scripts/find-uname.py
==============================================================================
--- python/branches/py3k/Demo/scripts/find-uname.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,40 +0,0 @@
-#!/usr/bin/env python3
-
-"""
-For each argument on the command line, look for it in the set of all Unicode
-names. Arguments are treated as case-insensitive regular expressions, e.g.:
-
- % find-uname 'small letter a$' 'horizontal line'
- *** small letter a$ matches ***
- LATIN SMALL LETTER A (97)
- COMBINING LATIN SMALL LETTER A (867)
- CYRILLIC SMALL LETTER A (1072)
- PARENTHESIZED LATIN SMALL LETTER A (9372)
- CIRCLED LATIN SMALL LETTER A (9424)
- FULLWIDTH LATIN SMALL LETTER A (65345)
- *** horizontal line matches ***
- HORIZONTAL LINE EXTENSION (9135)
-"""
-
-import unicodedata
-import sys
-import re
-
-def main(args):
- unicode_names = []
- for ix in range(sys.maxunicode+1):
- try:
- unicode_names.append((ix, unicodedata.name(chr(ix))))
- except ValueError: # no name for the character
- pass
- for arg in args:
- pat = re.compile(arg, re.I)
- matches = [(y,x) for (x,y) in unicode_names
- if pat.search(y) is not None]
- if matches:
- print("***", arg, "matches", "***")
- for match in matches:
- print("%s (%d)" % match)
-
-if __name__ == "__main__":
- main(sys.argv[1:])
Deleted: python/branches/py3k/Demo/scripts/from.py
==============================================================================
--- python/branches/py3k/Demo/scripts/from.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,35 +0,0 @@
-#! /usr/bin/env python3
-
-# Print From and Subject of messages in $MAIL.
-# Extension to multiple mailboxes and other bells & whistles are left
-# as exercises for the reader.
-
-import sys, os
-
-# Open mailbox file. Exits with exception when this fails.
-
-try:
- mailbox = os.environ['MAIL']
-except (AttributeError, KeyError):
- sys.stderr.write('No environment variable $MAIL\n')
- sys.exit(2)
-
-try:
- mail = open(mailbox)
-except IOError:
- sys.exit('Cannot open mailbox file: ' + mailbox)
-
-while 1:
- line = mail.readline()
- if not line:
- break # EOF
- if line.startswith('From '):
- # Start of message found
- print(line[:-1], end=' ')
- while 1:
- line = mail.readline()
- if not line or line == '\n':
- break
- if line.startswith('Subject: '):
- print(repr(line[9:-1]), end=' ')
- print()
Deleted: python/branches/py3k/Demo/scripts/lpwatch.py
==============================================================================
--- python/branches/py3k/Demo/scripts/lpwatch.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,102 +0,0 @@
-#! /usr/bin/env python3
-
-# Watch line printer queue(s).
-# Intended for BSD 4.3 lpq.
-
-import os
-import sys
-import time
-
-DEF_PRINTER = 'psc'
-DEF_DELAY = 10
-
-def main():
- delay = DEF_DELAY # XXX Use getopt() later
- try:
- thisuser = os.environ['LOGNAME']
- except:
- thisuser = os.environ['USER']
- printers = sys.argv[1:]
- if printers:
- # Strip '-P' from printer names just in case
- # the user specified it...
- for i, name in enumerate(printers):
- if name[:2] == '-P':
- printers[i] = name[2:]
- else:
- if 'PRINTER' in os.environ:
- printers = [os.environ['PRINTER']]
- else:
- printers = [DEF_PRINTER]
-
- clearhome = os.popen('clear', 'r').read()
-
- while True:
- text = clearhome
- for name in printers:
- text += makestatus(name, thisuser) + '\n'
- print(text)
- time.sleep(delay)
-
-def makestatus(name, thisuser):
- pipe = os.popen('lpq -P' + name + ' 2>&1', 'r')
- lines = []
- users = {}
- aheadbytes = 0
- aheadjobs = 0
- userseen = False
- totalbytes = 0
- totaljobs = 0
- for line in pipe:
- fields = line.split()
- n = len(fields)
- if len(fields) >= 6 and fields[n-1] == 'bytes':
- rank, user, job = fields[0:3]
- files = fields[3:-2]
- bytes = int(fields[n-2])
- if user == thisuser:
- userseen = True
- elif not userseen:
- aheadbytes += bytes
- aheadjobs += 1
- totalbytes += bytes
- totaljobs += 1
- ujobs, ubytes = users.get(user, (0, 0))
- ujobs += 1
- ubytes += bytes
- users[user] = ujobs, ubytes
- else:
- if fields and fields[0] != 'Rank':
- line = line.strip()
- if line == 'no entries':
- line = name + ': idle'
- elif line[-22:] == ' is ready and printing':
- line = name
- lines.append(line)
-
- if totaljobs:
- line = '%d K' % ((totalbytes+1023) // 1024)
- if totaljobs != len(users):
- line += ' (%d jobs)' % totaljobs
- if len(users) == 1:
- line += ' for %s' % next(iter(users))
- else:
- line += ' for %d users' % len(users)
- if userseen:
- if aheadjobs == 0:
- line += ' (%s first)' % thisuser
- else:
- line += ' (%d K before %s)' % (
- (aheadbytes+1023) // 1024, thisuser)
- lines.append(line)
-
- sts = pipe.close()
- if sts:
- lines.append('lpq exit status %r' % (sts,))
- return ': '.join(lines)
-
-if __name__ == "__main__":
- try:
- main()
- except KeyboardInterrupt:
- pass
Deleted: python/branches/py3k/Demo/scripts/makedir.py
==============================================================================
--- python/branches/py3k/Demo/scripts/makedir.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,21 +0,0 @@
-#! /usr/bin/env python3
-
-# Like mkdir, but also make intermediate directories if necessary.
-# It is not an error if the given directory already exists (as long
-# as it is a directory).
-# Errors are not treated specially -- you just get a Python exception.
-
-import sys, os
-
-def main():
- for p in sys.argv[1:]:
- makedirs(p)
-
-def makedirs(p):
- if p and not os.path.isdir(p):
- head, tail = os.path.split(p)
- makedirs(head)
- os.mkdir(p, 0o777)
-
-if __name__ == "__main__":
- main()
Deleted: python/branches/py3k/Demo/scripts/mboxconvert.py
==============================================================================
--- python/branches/py3k/Demo/scripts/mboxconvert.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,124 +0,0 @@
-#! /usr/bin/env python3
-
-# Convert MH directories (1 message per file) or MMDF mailboxes (4x^A
-# delimited) to unix mailbox (From ... delimited) on stdout.
-# If -f is given, files contain one message per file (e.g. MH messages)
-
-import rfc822
-import sys
-import time
-import os
-import stat
-import getopt
-import re
-
-def main():
- dofile = mmdf
- try:
- opts, args = getopt.getopt(sys.argv[1:], 'f')
- except getopt.error as msg:
- sys.stderr.write('%s\n' % msg)
- sys.exit(2)
- for o, a in opts:
- if o == '-f':
- dofile = message
- if not args:
- args = ['-']
- sts = 0
- for arg in args:
- if arg == '-' or arg == '':
- sts = dofile(sys.stdin) or sts
- elif os.path.isdir(arg):
- sts = mh(arg) or sts
- elif os.path.isfile(arg):
- try:
- f = open(arg)
- except IOError as msg:
- sys.stderr.write('%s: %s\n' % (arg, msg))
- sts = 1
- continue
- sts = dofile(f) or sts
- f.close()
- else:
- sys.stderr.write('%s: not found\n' % arg)
- sts = 1
- if sts:
- sys.exit(sts)
-
-numeric = re.compile('[1-9][0-9]*')
-
-def mh(dir):
- sts = 0
- msgs = os.listdir(dir)
- for msg in msgs:
- if numeric.match(msg) != len(msg):
- continue
- fn = os.path.join(dir, msg)
- try:
- f = open(fn)
- except IOError as msg:
- sys.stderr.write('%s: %s\n' % (fn, msg))
- sts = 1
- continue
- sts = message(f) or sts
- return sts
-
-def mmdf(f):
- sts = 0
- while 1:
- line = f.readline()
- if not line:
- break
- if line == '\1\1\1\1\n':
- sts = message(f, line) or sts
- else:
- sys.stderr.write(
- 'Bad line in MMFD mailbox: %r\n' % (line,))
- return sts
-
-counter = 0 # for generating unique Message-ID headers
-
-def message(f, delimiter = ''):
- sts = 0
- # Parse RFC822 header
- m = rfc822.Message(f)
- # Write unix header line
- fullname, email = m.getaddr('From')
- tt = m.getdate('Date')
- if tt:
- t = time.mktime(tt)
- else:
- sys.stderr.write(
- 'Unparseable date: %r\n' % (m.get('Date'),))
- t = os.fstat(f.fileno())[stat.ST_MTIME]
- print('From', email, time.ctime(t))
- # Copy RFC822 header
- for line in m.headers:
- print(line, end=' ')
- # Invent Message-ID header if none is present
- if 'message-id' not in m:
- global counter
- counter = counter + 1
- msgid = "<%s.%d>" % (hex(t), counter)
- sys.stderr.write("Adding Message-ID %s (From %s)\n" %
- (msgid, email))
- print("Message-ID:", msgid)
- print()
- # Copy body
- while 1:
- line = f.readline()
- if line == delimiter:
- break
- if not line:
- sys.stderr.write('Unexpected EOF in message\n')
- sts = 1
- break
- if line[:5] == 'From ':
- line = '>' + line
- print(line, end=' ')
- # Print trailing newline
- print()
- return sts
-
-if __name__ == "__main__":
- main()
Deleted: python/branches/py3k/Demo/scripts/morse.py
==============================================================================
--- python/branches/py3k/Demo/scripts/morse.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,128 +0,0 @@
-#! /usr/bin/env python3
-
-# DAH should be three DOTs.
-# Space between DOTs and DAHs should be one DOT.
-# Space between two letters should be one DAH.
-# Space between two words should be DOT DAH DAH.
-
-import sys, math, aifc
-from contextlib import closing
-
-DOT = 30
-DAH = 3 * DOT
-OCTAVE = 2 # 1 == 441 Hz, 2 == 882 Hz, ...
-
-morsetab = {
- 'A': '.-', 'a': '.-',
- 'B': '-...', 'b': '-...',
- 'C': '-.-.', 'c': '-.-.',
- 'D': '-..', 'd': '-..',
- 'E': '.', 'e': '.',
- 'F': '..-.', 'f': '..-.',
- 'G': '--.', 'g': '--.',
- 'H': '....', 'h': '....',
- 'I': '..', 'i': '..',
- 'J': '.---', 'j': '.---',
- 'K': '-.-', 'k': '-.-',
- 'L': '.-..', 'l': '.-..',
- 'M': '--', 'm': '--',
- 'N': '-.', 'n': '-.',
- 'O': '---', 'o': '---',
- 'P': '.--.', 'p': '.--.',
- 'Q': '--.-', 'q': '--.-',
- 'R': '.-.', 'r': '.-.',
- 'S': '...', 's': '...',
- 'T': '-', 't': '-',
- 'U': '..-', 'u': '..-',
- 'V': '...-', 'v': '...-',
- 'W': '.--', 'w': '.--',
- 'X': '-..-', 'x': '-..-',
- 'Y': '-.--', 'y': '-.--',
- 'Z': '--..', 'z': '--..',
- '0': '-----', ',': '--..--',
- '1': '.----', '.': '.-.-.-',
- '2': '..---', '?': '..--..',
- '3': '...--', ';': '-.-.-.',
- '4': '....-', ':': '---...',
- '5': '.....', "'": '.----.',
- '6': '-....', '-': '-....-',
- '7': '--...', '/': '-..-.',
- '8': '---..', '(': '-.--.-',
- '9': '----.', ')': '-.--.-',
- ' ': ' ', '_': '..--.-',
-}
-
-nowave = b'\0' * 200
-
-# If we play at 44.1 kHz (which we do), then if we produce one sine
-# wave in 100 samples, we get a tone of 441 Hz. If we produce two
-# sine waves in these 100 samples, we get a tone of 882 Hz. 882 Hz
-# appears to be a nice one for playing morse code.
-def mkwave(octave):
- sinewave = bytearray()
- for i in range(100):
- val = int(math.sin(math.pi * i * octave / 50.0) * 30000)
- sinewave.extend([(val >> 8) & 255, val & 255])
- return bytes(sinewave)
-
-defaultwave = mkwave(OCTAVE)
-
-def main():
- import getopt
- try:
- opts, args = getopt.getopt(sys.argv[1:], 'o:p:')
- except getopt.error:
- sys.stderr.write('Usage ' + sys.argv[0] +
- ' [ -o outfile ] [ -p octave ] [ words ] ...\n')
- sys.exit(1)
- wave = defaultwave
- outfile = 'morse.aifc'
- for o, a in opts:
- if o == '-o':
- outfile = a
- if o == '-p':
- wave = mkwave(int(a))
- with closing(aifc.open(outfile, 'w')) as fp:
- fp.setframerate(44100)
- fp.setsampwidth(2)
- fp.setnchannels(1)
- if args:
- source = [' '.join(args)]
- else:
- source = iter(sys.stdin.readline, '')
- for line in source:
- mline = morse(line)
- play(mline, fp, wave)
-
-# Convert a string to morse code with \001 between the characters in
-# the string.
-def morse(line):
- res = ''
- for c in line:
- try:
- res += morsetab[c] + '\001'
- except KeyError:
- pass
- return res
-
-# Play a line of morse code.
-def play(line, fp, wave):
- for c in line:
- if c == '.':
- sine(fp, DOT, wave)
- elif c == '-':
- sine(fp, DAH, wave)
- else: # space
- pause(fp, DAH + DOT)
- pause(fp, DOT)
-
-def sine(fp, length, wave):
- for i in range(length):
- fp.writeframesraw(wave)
-
-def pause(fp, length):
- for i in range(length):
- fp.writeframesraw(nowave)
-
-if __name__ == '__main__':
- main()
Deleted: python/branches/py3k/Demo/scripts/newslist.doc
==============================================================================
--- python/branches/py3k/Demo/scripts/newslist.doc Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,59 +0,0 @@
- NEWSLIST
- ========
- A program to assist HTTP browsing of newsgroups
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-WWW browsers such as NCSA Mosaic allow the user to read newsgroup
-articles by specifying the group name in a URL eg 'news:comp.answers'.
-
-To browse through many groups, though, (and there are several thousand
-of them) you really need a page or pages containing links to all the
-groups. There are some good ones out there, for example,
-
- http://info.cern.ch/hypertext/DataSources/News/Groups/Overview.html
-
-is the standard one at CERN, but it only shows the groups available there,
-which may be rather different from those available on your machine.
-
-Newslist is a program which creates a hierarchy of pages for you based
-on the groups available from YOUR server. It is written in python - a
-splendid interpreted object-oriented language which I suggest you get
-right now from the directory /pub/python at ftp.cwi.nl, if you haven't
-already got it.
-
-You should be able to see some sample output by looking at:
- http://pelican.cl.cam.ac.uk/newspage/root.html
-
-Descriptions of newsgroups can be added from a file with one group
-per line. eg:
-
- alt.foo Articles about foo
- comp.bar Programming in 'bar' and related languages
-
-A suitable list detailing most groups can be found at ftp.uu.net in
-/uunet-info/newsgroups.gz.
-
-Make sure you read the information at the beginning of the program source and
-configure the variables before running.
-
-In addition to python, you need:
-
- An NNTP-based news feed.
- A directory in which to put the pages.
-
-The programming is not very beautiful, but it works! It comes with no
-warranty, express or implied, but with the hope that some others may
-find it useful.
-
-Comments, improvements & suggestions welcomed.
-Quentin Stafford-Fraser
-
- ----------------------------------------------------------------------
- Quentin Stafford-Fraser
- http://pelican.cl.cam.ac.uk/people/qs101/me.html
-
- Cambridge University Computer Lab Rank Xerox Cambridge EuroPARC
- qs101(a)cl.cam.ac.uk fraser(a)europarc.xerox.com
- Tel: +44 223 334411 Tel: +44 223 341521
- Fax: +44 223 334679 Fax: +44 223 341510
- ----------------------------------------------------------------------
Deleted: python/branches/py3k/Demo/scripts/newslist.py
==============================================================================
--- python/branches/py3k/Demo/scripts/newslist.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,361 +0,0 @@
-#! /usr/bin/env python3
-#######################################################################
-# Newslist $Revision$
-#
-# Syntax:
-# newslist [ -a ]
-#
-# This is a program to create a directory full of HTML pages
-# which between them contain links to all the newsgroups available
-# on your server.
-#
-# The -a option causes a complete list of all groups to be read from
-# the server rather than just the ones which have appeared since last
-# execution. This recreates the local list from scratch. Use this on
-# the first invocation of the program, and from time to time thereafter.
-# When new groups are first created they may appear on your server as
-# empty groups. By default, empty groups are ignored by the -a option.
-# However, these new groups will not be created again, and so will not
-# appear in the server's list of 'new groups' at a later date. Hence it
-# won't appear until you do a '-a' after some articles have appeared.
-#
-# I should really keep a list of ignored empty groups and re-check them
-# for articles on every run, but I haven't got around to it yet.
-#
-# This assumes an NNTP news feed.
-#
-# Feel free to copy, distribute and modify this code for
-# non-commercial use. If you make any useful modifications, let me
-# know!
-#
-# (c) Quentin Stafford-Fraser 1994
-# fraser(a)europarc.xerox.com qs101(a)cl.cam.ac.uk
-# #
-#######################################################################
-import sys, nntplib, marshal, time, os
-
-#######################################################################
-# Check these variables before running! #
-
-# Top directory.
-# Filenames which don't start with / are taken as being relative to this.
-topdir = os.path.expanduser('~/newspage')
-
-# The name of your NNTP host
-# eg.
-# newshost = 'nntp-serv.cl.cam.ac.uk'
-# or use following to get the name from the NNTPSERVER environment
-# variable:
-# newshost = os.environ['NNTPSERVER']
-newshost = 'news.example.com'
-
-# The filename for a local cache of the newsgroup list
-treefile = 'grouptree'
-
-# The filename for descriptions of newsgroups
-# I found a suitable one at ftp.uu.net in /uunet-info/newgroups.gz
-# You can set this to '' if you don't wish to use one.
-descfile = 'newsgroups'
-
-# The directory in which HTML pages should be created
-# eg.
-# pagedir = '/usr/local/lib/html/newspage'
-# pagedir = 'pages'
-pagedir = topdir
-
-# The html prefix which will refer to this directory
-# eg.
-# httppref = '/newspage/',
-# or leave blank for relative links between pages: (Recommended)
-# httppref = ''
-httppref = ''
-
-# The name of the 'root' news page in this directory.
-# A .html suffix will be added.
-rootpage = 'root'
-
-# Set skipempty to 0 if you wish to see links to empty groups as well.
-# Only affects the -a option.
-skipempty = 1
-
-# pagelinkicon can contain html to put an icon after links to
-# further pages. This helps to make important links stand out.
-# Set to '' if not wanted, or '...' is quite a good one.
-pagelinkicon = '... <img src="http://pelican.cl.cam.ac.uk/icons/page.xbm"> '
-
-# ---------------------------------------------------------------------
-# Less important personal preferences:
-
-# Sublistsize controls the maximum number of items the will appear as
-# an indented sub-list before the whole thing is moved onto a different
-# page. The smaller this is, the more pages you will have, but the
-# shorter each will be.
-sublistsize = 4
-
-# That should be all. #
-#######################################################################
-
-for dir in os.curdir, os.environ['HOME']:
- rcfile = os.path.join(dir, '.newslistrc.py')
- if os.path.exists(rcfile):
- print(rcfile)
- exec(open(rcfile).read())
- break
-
-from nntplib import NNTP
-from stat import *
-
-rcsrev = '$Revision$'
-rcsrev = ' '.join([s for s in rcsrev.split() if '$' not in s])
-desc = {}
-
-# Make (possibly) relative filenames into absolute ones
-treefile = os.path.join(topdir,treefile)
-descfile = os.path.join(topdir,descfile)
-page = os.path.join(topdir,pagedir)
-
-# First the bits for creating trees ---------------------------
-
-# Addtotree creates/augments a tree from a list of group names
-def addtotree(tree, groups):
- print('Updating tree...')
- for i in groups:
- parts = i.split('.')
- makeleaf(tree, parts)
-
-# Makeleaf makes a leaf and the branch leading to it if necessary
-def makeleaf(tree,path):
- j = path[0]
- l = len(path)
-
- if j not in tree:
- tree[j] = {}
- if l == 1:
- tree[j]['.'] = '.'
- if l > 1:
- makeleaf(tree[j],path[1:])
-
-# Then the bits for outputting trees as pages ----------------
-
-# Createpage creates an HTML file named <root>.html containing links
-# to those groups beginning with <root>.
-
-def createpage(root, tree, p):
- filename = os.path.join(pagedir, root+'.html')
- if root == rootpage:
- detail = ''
- else:
- detail = ' under ' + root
- with open(filename, 'w') as f:
- # f.write('Content-Type: text/html\n')
- f.write('<html>\n<head>\n')
- f.write('<title>Newsgroups available%s</title>\n' % detail)
- f.write('</head>\n<body>\n')
- f.write('<h1>Newsgroups available%s</h1>\n' % detail)
- f.write('<a href="%s%s.html">Back to top level</a><p>\n' %
- (httppref, rootpage))
- printtree(f, tree, 0, p)
- f.write('\n<p>')
- f.write("<i>This page automatically created by 'newslist' v. %s." %
- rcsrev)
- f.write(time.ctime(time.time()) + '</i>\n')
- f.write('</body>\n</html>\n')
-
-# Printtree prints the groups as a bulleted list. Groups with
-# more than <sublistsize> subgroups will be put on a separate page.
-# Other sets of subgroups are just indented.
-
-def printtree(f, tree, indent, p):
- l = len(tree)
-
- if l > sublistsize and indent > 0:
- # Create a new page and a link to it
- f.write('<li><b><a href="%s%s.html">' % (httppref, p[1:]))
- f.write(p[1:] + '.*')
- f.write('</a></b>%s\n' % pagelinkicon)
- createpage(p[1:], tree, p)
- return
-
- kl = sorted(tree.keys())
-
- if l > 1:
- if indent > 0:
- # Create a sub-list
- f.write('<li>%s\n<ul>' % p[1:])
- else:
- # Create a main list
- f.write('<ul>')
- indent = indent + 1
-
- for i in kl:
- if i == '.':
- # Output a newsgroup
- f.write('<li><a href="news:%s">%s</a> ' % (p[1:], p[1:]))
- if p[1:] in desc:
- f.write(' <i>%s</i>\n' % desc[p[1:]])
- else:
- f.write('\n')
- else:
- # Output a hierarchy
- printtree(f, tree[i], indent, p+'.'+i)
-
- if l > 1:
- f.write('\n</ul>')
-
-# Reading descriptions file ---------------------------------------
-
-# This returns a dict mapping group name to its description
-
-def readdesc(descfile):
- global desc
- desc = {}
-
- if descfile == '':
- return
-
- try:
- with open(descfile, 'r') as d:
- print('Reading descriptions...')
- for l in d:
- bits = l.split()
- try:
- grp = bits[0]
- dsc = ' '.join(bits[1:])
- if len(dsc) > 1:
- desc[grp] = dsc
- except IndexError:
- pass
- except IOError:
- print('Failed to open description file ' + descfile)
- return
-
-# Check that ouput directory exists, ------------------------------
-# and offer to create it if not
-
-def checkopdir(pagedir):
- if not os.path.isdir(pagedir):
- print('Directory %s does not exist.' % pagedir)
- print('Shall I create it for you? (y/n)')
- if sys.stdin.readline()[0] == 'y':
- try:
- os.mkdir(pagedir, 0o777)
- except:
- print('Sorry - failed!')
- sys.exit(1)
- else:
- print('OK. Exiting.')
- sys.exit(1)
-
-# Read and write current local tree ----------------------------------
-
-def readlocallist(treefile):
- print('Reading current local group list...')
- tree = {}
- try:
- treetime = time.localtime(os.stat(treefile)[ST_MTIME])
- except:
- print('\n*** Failed to open local group cache '+treefile)
- print('If this is the first time you have run newslist, then')
- print('use the -a option to create it.')
- sys.exit(1)
- treedate = '%02d%02d%02d' % (treetime[0] % 100, treetime[1], treetime[2])
- try:
- with open(treefile, 'rb') as dump:
- tree = marshal.load(dump)
- except IOError:
- print('Cannot open local group list ' + treefile)
- return (tree, treedate)
-
-def writelocallist(treefile, tree):
- try:
- with open(treefile, 'wb') as dump:
- groups = marshal.dump(tree, dump)
- print('Saved list to %s\n' % treefile)
- except:
- print('Sorry - failed to write to local group cache', treefile)
- print('Does it (or its directory) have the correct permissions?')
- sys.exit(1)
-
-# Return list of all groups on server -----------------------------
-
-def getallgroups(server):
- print('Getting list of all groups...')
- treedate = '010101'
- info = server.list()[1]
- groups = []
- print('Processing...')
- if skipempty:
- print('\nIgnoring following empty groups:')
- for i in info:
- grpname = i[0].split()[0]
- if skipempty and int(i[1]) < int(i[2]):
- print(grpname.decode() + ' ', end=' ')
- else:
- groups.append(grpname.decode())
- print('\n')
- if skipempty:
- print('(End of empty groups)')
- return groups
-
-# Return list of new groups on server -----------------------------
-
-def getnewgroups(server, treedate):
- print('Getting list of new groups since start of %s...' % treedate, end=' ')
- info = server.newgroups(treedate, '000001')[1]
- print('got %d.' % len(info))
- print('Processing...', end=' ')
- groups = []
- for i in info:
- grpname = i.split()[0]
- groups.append(grpname.decode())
- print('Done')
- return groups
-
-# Now the main program --------------------------------------------
-
-def main():
- tree = {}
-
- # Check that the output directory exists
- checkopdir(pagedir)
-
- try:
- print('Connecting to %s...' % newshost)
- if sys.version[0] == '0':
- s = NNTP.init(newshost)
- else:
- s = NNTP(newshost)
- connected = True
- except (nntplib.error_temp, nntplib.error_perm) as x:
- print('Error connecting to host:', x)
- print('I\'ll try to use just the local list.')
- connected = False
-
- # If -a is specified, read the full list of groups from server
- if connected and len(sys.argv) > 1 and sys.argv[1] == '-a':
- groups = getallgroups(s)
-
- # Otherwise just read the local file and then add
- # groups created since local file last modified.
- else:
-
- (tree, treedate) = readlocallist(treefile)
- if connected:
- groups = getnewgroups(s, treedate)
-
- if connected:
- addtotree(tree, groups)
- writelocallist(treefile,tree)
-
- # Read group descriptions
- readdesc(descfile)
-
- print('Creating pages...')
- createpage(rootpage, tree, '')
- print('Done')
-
-if __name__ == "__main__":
- main()
-
-# That's all folks
-######################################################################
Deleted: python/branches/py3k/Demo/scripts/pi.py
==============================================================================
--- python/branches/py3k/Demo/scripts/pi.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,33 +0,0 @@
-#! /usr/bin/env python3
-
-# Print digits of pi forever.
-#
-# The algorithm, using Python's 'long' integers ("bignums"), works
-# with continued fractions, and was conceived by Lambert Meertens.
-#
-# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
-# published by Prentice-Hall (UK) Ltd., 1990.
-
-import sys
-
-def main():
- k, a, b, a1, b1 = 2, 4, 1, 12, 4
- while True:
- # Next approximation
- p, q, k = k*k, 2*k+1, k+1
- a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
- # Print common digits
- d, d1 = a//b, a1//b1
- while d == d1:
- output(d)
- a, a1 = 10*(a%b), 10*(a1%b1)
- d, d1 = a//b, a1//b1
-
-def output(d):
- # Use write() to avoid spaces between the digits
- sys.stdout.write(str(d))
- # Flush so the output is seen immediately
- sys.stdout.flush()
-
-if __name__ == "__main__":
- main()
Deleted: python/branches/py3k/Demo/scripts/pp.py
==============================================================================
--- python/branches/py3k/Demo/scripts/pp.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,125 +0,0 @@
-#! /usr/bin/env python3
-
-# Emulate some Perl command line options.
-# Usage: pp [-a] [-c] [-d] [-e scriptline] [-F fieldsep] [-n] [-p] [file] ...
-# Where the options mean the following:
-# -a : together with -n or -p, splits each line into list F
-# -c : check syntax only, do not execute any code
-# -d : run the script under the debugger, pdb
-# -e scriptline : gives one line of the Python script; may be repeated
-# -F fieldsep : sets the field separator for the -a option [not in Perl]
-# -n : runs the script for each line of input
-# -p : prints the line after the script has run
-# When no script lines have been passed, the first file argument
-# contains the script. With -n or -p, the remaining arguments are
-# read as input to the script, line by line. If a file is '-'
-# or missing, standard input is read.
-
-# XXX To do:
-# - add -i extension option (change files in place)
-# - make a single loop over the files and lines (changes effect of 'break')?
-# - add an option to specify the record separator
-# - except for -n/-p, run directly from the file if at all possible
-
-import sys
-import getopt
-
-FS = ''
-SCRIPT = []
-AFLAG = 0
-CFLAG = 0
-DFLAG = 0
-NFLAG = 0
-PFLAG = 0
-
-try:
- optlist, ARGS = getopt.getopt(sys.argv[1:], 'acde:F:np')
-except getopt.error as msg:
- sys.stderr.write('%s: %s\n' % (sys.argv[0], msg))
- sys.exit(2)
-
-for option, optarg in optlist:
- if option == '-a':
- AFLAG = 1
- elif option == '-c':
- CFLAG = 1
- elif option == '-d':
- DFLAG = 1
- elif option == '-e':
- for line in optarg.split('\n'):
- SCRIPT.append(line)
- elif option == '-F':
- FS = optarg
- elif option == '-n':
- NFLAG = 1
- PFLAG = 0
- elif option == '-p':
- NFLAG = 1
- PFLAG = 1
- else:
- print(option, 'not recognized???')
-
-if not ARGS: ARGS.append('-')
-
-if not SCRIPT:
- if ARGS[0] == '-':
- fp = sys.stdin
- else:
- fp = open(ARGS[0], 'r')
- while 1:
- line = fp.readline()
- if not line: break
- SCRIPT.append(line[:-1])
- del fp
- del ARGS[0]
- if not ARGS: ARGS.append('-')
-
-if CFLAG:
- prologue = ['if 0:']
- epilogue = []
-elif NFLAG:
- # Note that it is on purpose that AFLAG and PFLAG are
- # tested dynamically each time through the loop
- prologue = [
- 'LINECOUNT = 0',
- 'for FILE in ARGS:',
- ' \tif FILE == \'-\':',
- ' \t \tFP = sys.stdin',
- ' \telse:',
- ' \t \tFP = open(FILE, \'r\')',
- ' \tLINENO = 0',
- ' \twhile 1:',
- ' \t \tLINE = FP.readline()',
- ' \t \tif not LINE: break',
- ' \t \tLINENO = LINENO + 1',
- ' \t \tLINECOUNT = LINECOUNT + 1',
- ' \t \tL = LINE[:-1]',
- ' \t \taflag = AFLAG',
- ' \t \tif aflag:',
- ' \t \t \tif FS: F = L.split(FS)',
- ' \t \t \telse: F = L.split()'
- ]
- epilogue = [
- ' \t \tif not PFLAG: continue',
- ' \t \tif aflag:',
- ' \t \t \tif FS: print(FS.join(F))',
- ' \t \t \telse: print(\' \'.join(F))',
- ' \t \telse: print(L)',
- ]
-else:
- prologue = ['if 1:']
- epilogue = []
-
-# Note that we indent using tabs only, so that any indentation style
-# used in 'command' will come out right after re-indentation.
-
-program = '\n'.join(prologue) + '\n'
-for line in SCRIPT:
- program += ' \t \t' + line + '\n'
-program += '\n'.join(epilogue) + '\n'
-
-if DFLAG:
- import pdb
- pdb.run(program)
-else:
- exec(program)
Deleted: python/branches/py3k/Demo/scripts/primes.py
==============================================================================
--- python/branches/py3k/Demo/scripts/primes.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,31 +0,0 @@
-#! /usr/bin/env python3
-
-# Print prime numbers in a given range
-
-def primes(min, max):
- if max >= 2 >= min:
- print(2)
- primes = [2]
- i = 3
- while i <= max:
- for p in primes:
- if i % p == 0 or p*p > i:
- break
- if i % p != 0:
- primes.append(i)
- if i >= min:
- print(i)
- i += 2
-
-def main():
- import sys
- min, max = 2, 0x7fffffff
- if sys.argv[1:]:
- min = int(sys.argv[1])
- if sys.argv[2:]:
- max = int(sys.argv[2])
- primes(min, max)
-
-
-if __name__ == "__main__":
- main()
Deleted: python/branches/py3k/Demo/scripts/script.py
==============================================================================
--- python/branches/py3k/Demo/scripts/script.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,42 +0,0 @@
-#! /usr/bin/env python3
-
-# script.py -- Make typescript of terminal session.
-# Usage:
-# -a Append to typescript.
-# -p Use Python as shell.
-# Author: Steen Lumholt.
-
-
-import os, time, sys, getopt
-import pty
-
-def read(fd):
- data = os.read(fd, 1024)
- script.write(data)
- return data
-
-shell = 'sh'
-filename = 'typescript'
-mode = 'wb'
-if 'SHELL' in os.environ:
- shell = os.environ['SHELL']
-
-try:
- opts, args = getopt.getopt(sys.argv[1:], 'ap')
-except getopt.error as msg:
- print('%s: %s' % (sys.argv[0], msg))
- sys.exit(2)
-
-for o, a in opts:
- if o == '-a':
- mode = 'ab'
- elif o == '-p':
- shell = 'python'
-
-script = open(filename, mode)
-
-sys.stdout.write('Script started, file is %s\n' % filename)
-script.write(('Script started on %s\n' % time.ctime(time.time())).encode())
-pty.spawn(shell, read)
-script.write(('Script done on %s\n' % time.ctime(time.time())).encode())
-sys.stdout.write('Script done, file is %s\n' % filename)
Deleted: python/branches/py3k/Demo/scripts/update.py
==============================================================================
--- python/branches/py3k/Demo/scripts/update.py Thu Dec 30 18:22:33 2010
+++ (empty file)
@@ -1,92 +0,0 @@
-#! /usr/bin/env python3
-
-# Update a bunch of files according to a script.
-# The input file contains lines of the form <filename>:<lineno>:<text>,
-# meaning that the given line of the given file is to be replaced
-# by the given text. This is useful for performing global substitutions
-# on grep output:
-
-import os
-import sys
-import re
-
-pat = '^([^: \t\n]+):([1-9][0-9]*):'
-prog = re.compile(pat)
-
-class FileObj:
- def __init__(self, filename):
- self.filename = filename
- self.changed = 0
- try:
- self.lines = open(filename, 'r').readlines()
- except IOError as msg:
- print('*** Can\'t open "%s":' % filename, msg)
- self.lines = None
- return
- print('diffing', self.filename)
-
- def finish(self):
- if not self.changed:
- print('no changes to', self.filename)
- return
- try:
- os.rename(self.filename, self.filename + '~')
- fp = open(self.filename, 'w')
- except (os.error, IOError) as msg:
- print('*** Can\'t rewrite "%s":' % self.filename, msg)
- return
- print('writing', self.filename)
- for line in self.lines:
- fp.write(line)
- fp.close()
- self.changed = 0
-
- def process(self, lineno, rest):
- if self.lines is None:
- print('(not processed): %s:%s:%s' % (
- self.filename, lineno, rest), end=' ')
- return
- i = eval(lineno) - 1
- if not 0 <= i < len(self.lines):
- print('*** Line number out of range: %s:%s:%s' % (
- self.filename, lineno, rest), end=' ')
- return
- if self.lines[i] == rest:
- print('(no change): %s:%s:%s' % (
- self.filename, lineno, rest), end=' ')
- return
- if not self.changed:
- self.changed = 1
- print('%sc%s' % (lineno, lineno))
- print('<', self.lines[i], end=' ')
- print('---')
- self.lines[i] = rest
- print('>', self.lines[i], end=' ')
-
-def main():
- if sys.argv[1:]:
- try:
- fp = open(sys.argv[1], 'r')
- except IOError as msg:
- print('Can\'t open "%s":' % sys.argv[1], msg)
- sys.exit(1)
- else:
- fp = sys.stdin
- curfile = None
- while 1:
- line = fp.readline()
- if not line:
- if curfile: curfile.finish()
- break
- n = prog.match(line)
- if n < 0:
- print('Funny line:', line, end=' ')
- continue
- filename, lineno = prog.group(1, 2)
- if not curfile or filename != curfile.filename:
- if curfile: curfile.finish()
- curfile = FileObj(filename)
- curfile.process(lineno, line[n:])
-
-if __name__ == "__main__":
- main()
Modified: python/branches/py3k/Doc/library/pty.rst
==============================================================================
--- python/branches/py3k/Doc/library/pty.rst (original)
+++ python/branches/py3k/Doc/library/pty.rst Thu Dec 30 18:22:33 2010
@@ -45,3 +45,50 @@
a file descriptor. The defaults try to read 1024 bytes each time they are
called.
+
+Example
+-------
+
+.. sectionauthor:: Steen Lumholt
+
+The following program acts like the Unix command :manpage:`script(1)`, using a
+pseudo-terminal to record all input and output of a terminal session in a
+"typescript". ::
+
+ import sys, os, time, getopt
+ import pty
+
+ mode = 'wb'
+ shell = 'sh'
+ filename = 'typescript'
+ if 'SHELL' in os.environ:
+ shell = os.environ['SHELL']
+
+ try:
+ opts, args = getopt.getopt(sys.argv[1:], 'ap')
+ except getopt.error as msg:
+ print('%s: %s' % (sys.argv[0], msg))
+ sys.exit(2)
+
+ for opt, arg in opts:
+ # option -a: append to typescript file
+ if opt == '-a':
+ mode = 'ab'
+ # option -p: use a Python shell as the terminal command
+ elif opt == '-p':
+ shell = sys.executable
+ if args:
+ filename = args[0]
+
+ script = open(filename, mode)
+
+ def read(fd):
+ data = os.read(fd, 1024)
+ script.write(data)
+ return data
+
+ sys.stdout.write('Script started, file is %s\n' % filename)
+ script.write(('Script started on %s\n' % time.asctime()).encode())
+ pty.spawn(shell, read)
+ script.write(('Script done on %s\n' % time.asctime()).encode())
+ sys.stdout.write('Script done, file is %s\n' % filename)
1
0
Author: martin.v.loewis
Date: Thu Dec 30 15:57:53 2010
New Revision: 87578
Log:
Clarify that libpython3.so is only meant for use in
applications.
Modified:
peps/trunk/pep-0384.txt
Modified: peps/trunk/pep-0384.txt
==============================================================================
--- peps/trunk/pep-0384.txt (original)
+++ peps/trunk/pep-0384.txt Thu Dec 30 15:57:53 2010
@@ -336,7 +336,9 @@
version check for the API version will accept either 3 or the current
PYTHON_API_VERSION as conforming. If Python is compiled as a shared
library, it is installed as both libpython3.so, and libpython3.y.so;
-applications conforming to this PEP should then link to the former.
+applications conforming to this PEP should then link to the former
+(extension modules can continue to link with no libpython shared object,
+but rather rely on runtime linking).
The ABI version is symbolically available as ``PYTHON_ABI_VERSION``.
Also on Unix, the PEP 3149 tag abi<PYTHON_ABI_VERSION> is accepted
1
0