Changeset 388 for python/vendor/current/Demo
- Timestamp:
- Mar 19, 2014, 11:11:30 AM (11 years ago)
- Location:
- python/vendor/current/Demo
- Files:
-
- 18 added
- 5 deleted
- 69 edited
Legend:
- Unmodified
- Added
- Removed
-
python/vendor/current/Demo/cgi/cgi1.py
r2 r388 1 #!/usr/ local/bin/python1 #!/usr/bin/env python 2 2 3 3 """CGI test 1 - check server setup.""" -
python/vendor/current/Demo/cgi/cgi2.py
r2 r388 1 #!/usr/ local/bin/python1 #!/usr/bin/env python 2 2 3 3 """CGI test 2 - basic use of cgi module.""" -
python/vendor/current/Demo/cgi/cgi3.py
r2 r388 1 #!/usr/ local/bin/python1 #!/usr/bin/env python 2 2 3 3 """CGI test 3 (persistent data).""" -
python/vendor/current/Demo/classes/Vec.py
r2 r388 1 # A simple vector class 1 class Vec: 2 """ A simple vector class 2 3 4 Instances of the Vec class can be constructed from numbers 3 5 4 def vec(*v): 5 return Vec(*v)6 >>> a = Vec(1, 2, 3) 7 >>> b = Vec(3, 2, 1) 6 8 9 added 10 >>> a + b 11 Vec(4, 4, 4) 7 12 8 class Vec: 13 subtracted 14 >>> a - b 15 Vec(-2, 0, 2) 9 16 17 and multiplied by a scalar on the left 18 >>> 3.0 * a 19 Vec(3.0, 6.0, 9.0) 20 21 or on the right 22 >>> a * 3.0 23 Vec(3.0, 6.0, 9.0) 24 """ 10 25 def __init__(self, *v): 11 26 self.v = list(v) 12 27 13 def fromlist(self, v): 28 @classmethod 29 def fromlist(cls, v): 14 30 if not isinstance(v, list): 15 31 raise TypeError 16 self.v = v[:] 17 return self 32 inst = cls() 33 inst.v = v 34 return inst 18 35 19 36 def __repr__(self): 20 return 'vec(' + repr(self.v)[1:-1] + ')' 37 args = ', '.join(repr(x) for x in self.v) 38 return 'Vec({0})'.format(args) 21 39 22 40 def __len__(self): … … 28 46 def __add__(self, other): 29 47 # Element-wise addition 30 v = map(lambda x, y: x+y, self, other)31 return Vec ().fromlist(v)48 v = [x + y for x, y in zip(self.v, other.v)] 49 return Vec.fromlist(v) 32 50 33 51 def __sub__(self, other): 34 52 # Element-wise subtraction 35 v = map(lambda x, y: x-y, self, other)36 return Vec ().fromlist(v)53 v = [x - y for x, y in zip(self.v, other.v)] 54 return Vec.fromlist(v) 37 55 38 56 def __mul__(self, scalar): 39 57 # Multiply by scalar 40 v = map(lambda x: x*scalar, self.v)41 return Vec ().fromlist(v)58 v = [x * scalar for x in self.v] 59 return Vec.fromlist(v) 42 60 61 __rmul__ = __mul__ 43 62 44 63 45 64 def test(): 46 a = vec(1, 2, 3) 47 b = vec(3, 2, 1) 48 print a 49 print b 50 print a+b 51 print a-b 52 print a*3.0 65 import doctest 66 doctest.testmod() 53 67 54 68 test() -
python/vendor/current/Demo/curses/ncurses.py
r2 r388 1 1 #!/usr/bin/env python 2 2 # 3 # $Id : ncurses.py 66424 2008-09-13 01:22:08Z andrew.kuchling$3 # $Id$ 4 4 # 5 5 # (n)curses exerciser in Python, an interactive test for the curses -
python/vendor/current/Demo/curses/rain.py
r2 r388 1 1 #!/usr/bin/env python 2 2 # 3 # $Id : rain.py 46625 2006-06-03 23:02:15Z andrew.kuchling$3 # $Id$ 4 4 # 5 5 # somebody should probably check the randrange()s... -
python/vendor/current/Demo/curses/tclock.py
r2 r388 1 1 #!/usr/bin/env python 2 2 # 3 # $Id : tclock.py 46626 2006-06-03 23:07:21Z andrew.kuchling$3 # $Id$ 4 4 # 5 5 # From tclock.c, Copyright Howard Jones <ha.jones@ic.ac.uk>, September 1994. -
python/vendor/current/Demo/curses/xmas.py
r2 r388 2 2 # December 1989 Larry Bartz Indianapolis, IN 3 3 # 4 # $Id : xmas.py 46623 2006-06-03 22:59:23Z andrew.kuchling$4 # $Id$ 5 5 # 6 6 # I'm dreaming of an ascii character-based monochrome Christmas, -
python/vendor/current/Demo/embed/Makefile
r2 r388 1 1 # Makefile for embedded Python use demo. 2 # (This version tailored for my Red Hat Linux 6.1 setup;2 # (This version originally written on Red Hat Linux 6.1; 3 3 # edit lines marked with XXX.) 4 4 … … 11 11 12 12 # Python version 13 VERSION= 2. 613 VERSION= 2.7 14 14 15 15 # Compiler flags … … 22 22 LIBPYTHON= $(blddir)/libpython$(VERSION).a 23 23 24 # XXX edit LIBS (in particular) to match $(blddir)/M odules/Makefile24 # XXX edit LIBS (in particular) to match $(blddir)/Makefile 25 25 LIBS= -lnsl -ldl -lreadline -ltermcap -lieee -lpthread -lutil 26 26 LDFLAGS= -Xlinker -export-dynamic -
python/vendor/current/Demo/embed/demo.c
r2 r388 7 7 main(int argc, char **argv) 8 8 { 9 10 9 /* Pass argv[0] to the Python interpreter */ 10 Py_SetProgramName(argv[0]); 11 11 12 13 12 /* Initialize the Python interpreter. Required. */ 13 Py_Initialize(); 14 14 15 16 15 /* Add a static module */ 16 initxyzzy(); 17 17 18 /* Define sys.argv. It is up to the application if you 19 want this; you can also let it undefined (since the Python 20 code is generally not a main program it has no business 21 touching sys.argv...) */ 22 PySys_SetArgv(argc, argv); 18 /* Define sys.argv. It is up to the application if you 19 want this; you can also leave it undefined (since the Python 20 code is generally not a main program it has no business 21 touching sys.argv...) 23 22 24 /* Do some application specific code */ 25 printf("Hello, brave new world\n\n"); 23 If the third argument is true, sys.path is modified to include 24 either the directory containing the script named by argv[0], or 25 the current working directory. This can be risky; if you run 26 an application embedding Python in a directory controlled by 27 someone else, attackers could put a Trojan-horse module in the 28 directory (say, a file named os.py) that your application would 29 then import and run. 30 */ 31 PySys_SetArgvEx(argc, argv, 0); 26 32 27 /* Execute some Python statements (in module __main__) */ 28 PyRun_SimpleString("import sys\n"); 29 PyRun_SimpleString("print sys.builtin_module_names\n"); 30 PyRun_SimpleString("print sys.modules.keys()\n"); 31 PyRun_SimpleString("print sys.executable\n"); 32 PyRun_SimpleString("print sys.argv\n"); 33 /* Do some application specific code */ 34 printf("Hello, brave new world\n\n"); 33 35 34 /* Note that you can call any public function of the Python 35 interpreter here, e.g. call_object(). */ 36 /* Execute some Python statements (in module __main__) */ 37 PyRun_SimpleString("import sys\n"); 38 PyRun_SimpleString("print sys.builtin_module_names\n"); 39 PyRun_SimpleString("print sys.modules.keys()\n"); 40 PyRun_SimpleString("print sys.executable\n"); 41 PyRun_SimpleString("print sys.argv\n"); 36 42 37 /* Some more application specific code */ 38 printf("\nGoodbye, cruel world\n"); 43 /* Note that you can call any public function of the Python 44 interpreter here, e.g. call_object(). */ 39 45 40 /* Exit, cleaning up the interpreter */ 41 Py_Exit(0); 42 /*NOTREACHED*/ 46 /* Some more application specific code */ 47 printf("\nGoodbye, cruel world\n"); 48 49 /* Exit, cleaning up the interpreter */ 50 Py_Exit(0); 51 /*NOTREACHED*/ 43 52 } 44 53 … … 49 58 xyzzy_foo(PyObject *self, PyObject* args) 50 59 { 51 60 return PyInt_FromLong(42L); 52 61 } 53 62 54 63 static PyMethodDef xyzzy_methods[] = { 55 {"foo", xyzzy_foo,METH_NOARGS,56 57 {NULL, NULL}/* sentinel */64 {"foo", xyzzy_foo, METH_NOARGS, 65 "Return the meaning of everything."}, 66 {NULL, NULL} /* sentinel */ 58 67 }; 59 68 … … 61 70 initxyzzy(void) 62 71 { 63 64 72 PyImport_AddModule("xyzzy"); 73 Py_InitModule("xyzzy", xyzzy_methods); 65 74 } -
python/vendor/current/Demo/embed/loop.c
r2 r388 7 7 main(int argc, char **argv) 8 8 { 9 10 9 int count = -1; 10 char *command; 11 11 12 13 14 15 16 12 if (argc < 2 || argc > 3) { 13 fprintf(stderr, "usage: loop <python-command> [count]\n"); 14 exit(2); 15 } 16 command = argv[1]; 17 17 18 19 20 18 if (argc == 3) { 19 count = atoi(argv[2]); 20 } 21 21 22 22 Py_SetProgramName(argv[0]); 23 23 24 25 24 /* uncomment this if you don't want to load site.py */ 25 /* Py_NoSiteFlag = 1; */ 26 26 27 28 29 30 31 32 27 while (count == -1 || --count >= 0 ) { 28 Py_Initialize(); 29 PyRun_SimpleString(command); 30 Py_Finalize(); 31 } 32 return 0; 33 33 } -
python/vendor/current/Demo/newmetaclasses/Eiffel.py
r2 r388 30 30 post = dict.get("%s_post" % m) 31 31 if pre or post: 32 dict[ k] = cls.make_eiffel_method(dict[m], pre, post)32 dict[m] = cls.make_eiffel_method(dict[m], pre, post) 33 33 34 34 class EiffelMetaClass1(EiffelBaseMetaClass): -
python/vendor/current/Demo/parser/README
r2 r388 7 7 ------ 8 8 9 FILES-- list of files associated with the parser module.9 FILES -- list of files associated with the parser module. 10 10 11 README-- this file.11 README -- this file. 12 12 13 example.py -- module that uses the `parser' module to extract 14 information from the parse tree of Python source 15 code. 13 docstring.py -- sample source file containing only a module docstring. 16 14 17 docstring.py -- sample source file containing only a module docstring. 15 example.py -- module that uses the `parser' module to extract 16 information from the parse tree of Python source 17 code. 18 18 19 19 simple.py -- sample source containing a "short form" definition. 20 20 21 source.py --sample source code used to demonstrate ability to22 23 21 source.py -- sample source code used to demonstrate ability to 22 handle nested constructs easily using the functions 23 and classes in example.py. 24 24 25 25 test_parser.py program to put the parser module through its paces. 26 26 27 unparse.py AST (2.5) based example to recreate source code 28 from an AST. This is incomplete; contributions 29 are welcome. 27 test_unparse.py tests for the unparse module 28 29 unparse.py AST (2.7) based example to recreate source code 30 from an AST. 30 31 31 32 Enjoy! -
python/vendor/current/Demo/parser/test_parser.py
r2 r388 12 12 print '----', fileName, 13 13 try: 14 ast = parser.suite(t)15 tup = parser. ast2tuple(ast)16 # this discards the first AST; a huge memory savings when running14 st = parser.suite(t) 15 tup = parser.st2tuple(st) 16 # this discards the first ST; a huge memory savings when running 17 17 # against a large source file like Tkinter.py. 18 ast = None19 new = parser.tuple2 ast(tup)18 st = None 19 new = parser.tuple2st(tup) 20 20 except parser.ParserError, err: 21 21 print … … 24 24 _numFailed = _numFailed + 1 25 25 else: 26 if tup != parser. ast2tuple(new):26 if tup != parser.st2tuple(new): 27 27 print 28 28 print 'parser module failed on input file', fileName -
python/vendor/current/Demo/parser/unparse.py
r2 r388 1 1 "Usage: unparse.py <path to source file>" 2 2 import sys 3 import _ast3 import ast 4 4 import cStringIO 5 5 import os 6 7 # Large float and imaginary literals get turned into infinities in the AST. 8 # We unparse those infinities to INFSTR. 9 INFSTR = "1e" + repr(sys.float_info.max_10_exp + 1) 6 10 7 11 def interleave(inter, f, seq): … … 10 14 seq = iter(seq) 11 15 try: 12 f( seq.next())16 f(next(seq)) 13 17 except StopIteration: 14 18 pass … … 21 25 """Methods in this class recursively traverse an AST and 22 26 output source code for the abstract syntax; original formatting 23 is disregar ged. """27 is disregarded. """ 24 28 25 29 def __init__(self, tree, file = sys.stdout): … … 27 31 Print the source for tree to file.""" 28 32 self.f = file 33 self.future_imports = [] 29 34 self._indent = 0 30 35 self.dispatch(tree) 31 print >>self.f,""36 self.f.write("") 32 37 self.f.flush() 33 38 … … 80 85 81 86 def _ImportFrom(self, t): 87 # A from __future__ import may affect unparsing, so record it. 88 if t.module and t.module == '__future__': 89 self.future_imports.extend(n.name for n in t.names) 90 82 91 self.fill("from ") 83 self.write(t.module) 92 self.write("." * t.level) 93 if t.module: 94 self.write(t.module) 84 95 self.write(" import ") 85 96 interleave(lambda: self.write(", "), self.dispatch, t.names) 86 # XXX(jpe) what is level for?87 97 88 98 def _Assign(self, t): … … 116 126 def _Delete(self, t): 117 127 self.fill("del ") 118 self.dispatch(t.targets)128 interleave(lambda: self.write(", "), self.dispatch, t.targets) 119 129 120 130 def _Assert(self, t): … … 187 197 188 198 def _TryFinally(self, t): 189 self.fill("try") 190 self.enter() 191 self.dispatch(t.body) 192 self.leave() 199 if len(t.body) == 1 and isinstance(t.body[0], ast.TryExcept): 200 # try-except-finally 201 self.dispatch(t.body) 202 else: 203 self.fill("try") 204 self.enter() 205 self.dispatch(t.body) 206 self.leave() 193 207 194 208 self.fill("finally") … … 203 217 self.dispatch(t.type) 204 218 if t.name: 205 self.write(" ,")219 self.write(" as ") 206 220 self.dispatch(t.name) 207 221 self.enter() … … 211 225 def _ClassDef(self, t): 212 226 self.write("\n") 227 for deco in t.decorator_list: 228 self.fill("@") 229 self.dispatch(deco) 213 230 self.fill("class "+t.name) 214 231 if t.bases: … … 246 263 self.enter() 247 264 self.dispatch(t.orelse) 248 self.leave 265 self.leave() 249 266 250 267 def _If(self, t): … … 252 269 self.dispatch(t.test) 253 270 self.enter() 254 # XXX elif? 255 self.dispatch(t.body) 256 self.leave() 271 self.dispatch(t.body) 272 self.leave() 273 # collapse nested ifs into equivalent elifs. 274 while (t.orelse and len(t.orelse) == 1 and 275 isinstance(t.orelse[0], ast.If)): 276 t = t.orelse[0] 277 self.fill("elif ") 278 self.dispatch(t.test) 279 self.enter() 280 self.dispatch(t.body) 281 self.leave() 282 # final else 257 283 if t.orelse: 258 284 self.fill("else") … … 271 297 self.enter() 272 298 self.dispatch(t.orelse) 273 self.leave 299 self.leave() 274 300 275 301 def _With(self, t): … … 285 311 # expr 286 312 def _Str(self, tree): 287 self.write(repr(tree.s)) 313 # if from __future__ import unicode_literals is in effect, 314 # then we want to output string literals using a 'b' prefix 315 # and unicode literals with no prefix. 316 if "unicode_literals" not in self.future_imports: 317 self.write(repr(tree.s)) 318 elif isinstance(tree.s, str): 319 self.write("b" + repr(tree.s)) 320 elif isinstance(tree.s, unicode): 321 self.write(repr(tree.s).lstrip("u")) 322 else: 323 assert False, "shouldn't get here" 288 324 289 325 def _Name(self, t): … … 296 332 297 333 def _Num(self, t): 298 self.write(repr(t.n)) 334 repr_n = repr(t.n) 335 # Parenthesize negative numbers, to avoid turning (-1)**2 into -1**2. 336 if repr_n.startswith("-"): 337 self.write("(") 338 # Substitute overflowing decimal literal for AST infinities. 339 self.write(repr_n.replace("inf", INFSTR)) 340 if repr_n.startswith("-"): 341 self.write(")") 299 342 300 343 def _List(self, t): … … 316 359 self.dispatch(gen) 317 360 self.write(")") 361 362 def _SetComp(self, t): 363 self.write("{") 364 self.dispatch(t.elt) 365 for gen in t.generators: 366 self.dispatch(gen) 367 self.write("}") 368 369 def _DictComp(self, t): 370 self.write("{") 371 self.dispatch(t.key) 372 self.write(": ") 373 self.dispatch(t.value) 374 for gen in t.generators: 375 self.dispatch(gen) 376 self.write("}") 318 377 319 378 def _comprehension(self, t): … … 335 394 self.write(")") 336 395 396 def _Set(self, t): 397 assert(t.elts) # should be at least one element 398 self.write("{") 399 interleave(lambda: self.write(", "), self.dispatch, t.elts) 400 self.write("}") 401 337 402 def _Dict(self, t): 338 403 self.write("{") 339 def writem((k, v)): 404 def write_pair(pair): 405 (k, v) = pair 340 406 self.dispatch(k) 341 407 self.write(": ") 342 408 self.dispatch(v) 343 interleave(lambda: self.write(", "), write m, zip(t.keys, t.values))409 interleave(lambda: self.write(", "), write_pair, zip(t.keys, t.values)) 344 410 self.write("}") 345 411 … … 356 422 unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"} 357 423 def _UnaryOp(self, t): 424 self.write("(") 358 425 self.write(self.unop[t.op.__class__.__name__]) 359 self.write("(") 360 self.dispatch(t.operand) 426 self.write(" ") 427 # If we're applying unary minus to a number, parenthesize the number. 428 # This is necessary: -2147483648 is different from -(2147483648) on 429 # a 32-bit machine (the first is an int, the second a long), and 430 # -7j is different from -(7j). (The first has real part 0.0, the second 431 # has real part -0.0.) 432 if isinstance(t.op, ast.USub) and isinstance(t.operand, ast.Num): 433 self.write("(") 434 self.dispatch(t.operand) 435 self.write(")") 436 else: 437 self.dispatch(t.operand) 361 438 self.write(")") 362 439 363 440 binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%", 364 "LShift":" >>", "RShift":"<<", "BitOr":"|", "BitXor":"^", "BitAnd":"&",441 "LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&", 365 442 "FloorDiv":"//", "Pow": "**"} 366 443 def _BinOp(self, t): … … 379 456 self.write(" " + self.cmpops[o.__class__.__name__] + " ") 380 457 self.dispatch(e) 381 382 383 boolops = { _ast.And: 'and', _ast.Or: 'or'}458 self.write(")") 459 460 boolops = {ast.And: 'and', ast.Or: 'or'} 384 461 def _BoolOp(self, t): 385 462 self.write("(") … … 390 467 def _Attribute(self,t): 391 468 self.dispatch(t.value) 469 # Special case: 3.__abs__() is a syntax error, so if t.value 470 # is an integer literal then we need to either parenthesize 471 # it or add an extra space to get 3 .__abs__(). 472 if isinstance(t.value, ast.Num) and isinstance(t.value.n, int): 473 self.write(" ") 392 474 self.write(".") 393 475 self.write(t.attr) … … 446 528 def _arguments(self, t): 447 529 first = True 448 nonDef = len(t.args)-len(t.defaults) 449 for a in t.args[0:nonDef]: 450 if first:first = False 451 else: self.write(", ") 452 self.dispatch(a) 453 for a,d in zip(t.args[nonDef:], t.defaults): 530 # normal arguments 531 defaults = [None] * (len(t.args) - len(t.defaults)) + t.defaults 532 for a,d in zip(t.args, defaults): 454 533 if first:first = False 455 534 else: self.write(", ") 456 535 self.dispatch(a), 457 self.write("=") 458 self.dispatch(d) 536 if d: 537 self.write("=") 538 self.dispatch(d) 539 540 # varargs 459 541 if t.vararg: 460 542 if first:first = False 461 543 else: self.write(", ") 462 self.write("*"+t.vararg) 544 self.write("*") 545 self.write(t.vararg) 546 547 # kwargs 463 548 if t.kwarg: 464 549 if first:first = False … … 472 557 473 558 def _Lambda(self, t): 559 self.write("(") 474 560 self.write("lambda ") 475 561 self.dispatch(t.args) 476 562 self.write(": ") 477 563 self.dispatch(t.body) 564 self.write(")") 478 565 479 566 def _alias(self, t): … … 483 570 484 571 def roundtrip(filename, output=sys.stdout): 485 source = open(filename).read() 486 tree = compile(source, filename, "exec", _ast.PyCF_ONLY_AST) 572 with open(filename, "r") as pyfile: 573 source = pyfile.read() 574 tree = compile(source, filename, "exec", ast.PyCF_ONLY_AST) 487 575 Unparser(tree, output) 488 576 … … 493 581 names = [n for n in os.listdir(a) if n.endswith('.py')] 494 582 except OSError: 495 print >> sys.stderr, "Directory not readable: %s" % a583 sys.stderr.write("Directory not readable: %s" % a) 496 584 else: 497 585 for n in names: … … 502 590 try: 503 591 roundtrip(fullname, output) 504 except Exception ,e:592 except Exception as e: 505 593 print ' Failed to compile, exception is %s' % repr(e) 506 594 elif os.path.isdir(fullname): -
python/vendor/current/Demo/pdist/FSProxy.py
r2 r388 24 24 import fnmatch 25 25 26 if os.name == 'mac': 27 import macfs 28 maxnamelen = 31 29 else: 30 macfs = None 31 maxnamelen = 255 26 maxnamelen = 255 32 27 33 28 skipnames = (os.curdir, os.pardir) … … 64 59 65 60 def _hidden(self, name): 66 if os.name == 'mac': 67 return name[0] == '(' and name[-1] == ')' 68 else: 69 return name[0] == '.' 61 return name[0] == '.' 70 62 71 63 def _hide(self, name): 72 if os.name == 'mac': 73 return '(%s)' % name 74 else: 75 return '.%s' % name 64 return '.%s' % name 76 65 77 66 def visible(self, name): … … 82 71 head, tail = os.path.split(name) 83 72 if head or not tail: return 0 84 if macfs: 85 if os.path.exists(name) and not os.path.isdir(name): 86 try: 87 fs = macfs.FSSpec(name) 88 c, t = fs.GetCreatorType() 89 if t != 'TEXT': return 0 90 except macfs.error, msg: 91 print "***", name, msg 92 return 0 93 else: 94 if os.path.islink(name): return 0 95 if '\0' in open(name, 'rb').read(512): return 0 73 if os.path.islink(name): return 0 74 if '\0' in open(name, 'rb').read(512): return 0 96 75 for ign in self._ignore: 97 76 if fnmatch.fnmatch(name, ign): return 0 -
python/vendor/current/Demo/pysvr/pysvr.c
r2 r388 35 35 36 36 struct workorder { 37 38 37 int conn; 38 struct sockaddr_in addr; 39 39 }; 40 40 … … 56 56 main(int argc, char **argv) 57 57 { 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 58 int port = PORT; 59 int c; 60 61 if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0') 62 progname = argv[0]; 63 64 while ((c = getopt(argc, argv, "v")) != EOF) { 65 switch (c) { 66 case 'v': 67 Py_VerboseFlag++; 68 break; 69 default: 70 usage(); 71 } 72 } 73 74 if (optind < argc) { 75 if (optind+1 < argc) { 76 oprogname(); 77 fprintf(stderr, "too many arguments\n"); 78 usage(); 79 } 80 port = atoi(argv[optind]); 81 if (port <= 0) { 82 fprintf(stderr, "bad port (%s)\n", argv[optind]); 83 usage(); 84 } 85 } 86 87 main_thread(port); 88 89 fprintf(stderr, "Bye.\n"); 90 91 exit(0); 92 92 } 93 93 … … 97 97 usage(void) 98 98 { 99 100 99 fprintf(stderr, usage_line, progname); 100 exit(2); 101 101 } 102 102 … … 104 104 main_thread(int port) 105 105 { 106 107 108 109 110 111 112 113 114 106 int sock, conn, size, i; 107 struct sockaddr_in addr, clientaddr; 108 109 sock = socket(PF_INET, SOCK_STREAM, 0); 110 if (sock < 0) { 111 oprogname(); 112 perror("can't create socket"); 113 exit(1); 114 } 115 115 116 116 #ifdef SO_REUSEADDR 117 118 117 i = 1; 118 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i); 119 119 #endif 120 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 121 memset((char *)&addr, '\0', sizeof addr); 122 addr.sin_family = AF_INET; 123 addr.sin_port = htons(port); 124 addr.sin_addr.s_addr = 0L; 125 if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) { 126 oprogname(); 127 perror("can't bind socket to address"); 128 exit(1); 129 } 130 131 if (listen(sock, 5) < 0) { 132 oprogname(); 133 perror("can't listen on socket"); 134 exit(1); 135 } 136 137 fprintf(stderr, "Listening on port %d...\n", port); 138 139 for (i = 0; ; i++) { 140 size = sizeof clientaddr; 141 memset((char *) &clientaddr, '\0', size); 142 conn = accept(sock, (struct sockaddr *) &clientaddr, &size); 143 if (conn < 0) { 144 oprogname(); 145 perror("can't accept connection from socket"); 146 exit(1); 147 } 148 149 size = sizeof addr; 150 memset((char *) &addr, '\0', size); 151 if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) { 152 oprogname(); 153 perror("can't get socket name of connection"); 154 exit(1); 155 } 156 if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) { 157 oprogname(); 158 perror("connection from non-local host refused"); 159 fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n", 160 ntohl(addr.sin_addr.s_addr), 161 ntohl(clientaddr.sin_addr.s_addr)); 162 close(conn); 163 continue; 164 } 165 if (i == 4) { 166 close(conn); 167 break; 168 } 169 create_thread(conn, &clientaddr); 170 } 171 172 close(sock); 173 174 if (gtstate) { 175 PyEval_AcquireThread(gtstate); 176 gtstate = NULL; 177 Py_Finalize(); 178 /* And a second time, just because we can. */ 179 Py_Finalize(); /* This should be harmless. */ 180 } 181 exit(0); 182 182 } 183 183 … … 185 185 create_thread(int conn, struct sockaddr_in *addr) 186 186 { 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 187 struct workorder *work; 188 pthread_t tdata; 189 190 work = malloc(sizeof(struct workorder)); 191 if (work == NULL) { 192 oprogname(); 193 fprintf(stderr, "out of memory for thread.\n"); 194 close(conn); 195 return; 196 } 197 work->conn = conn; 198 work->addr = *addr; 199 200 init_python(); 201 202 if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) { 203 oprogname(); 204 perror("can't create new thread"); 205 close(conn); 206 return; 207 } 208 209 if (pthread_detach(tdata) < 0) { 210 oprogname(); 211 perror("can't detach from thread"); 212 } 213 213 } 214 214 … … 220 220 init_python(void) 221 221 { 222 223 224 225 226 222 if (gtstate) 223 return; 224 Py_Initialize(); /* Initialize the interpreter */ 225 PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */ 226 gtstate = PyEval_SaveThread(); /* Release the thread state */ 227 227 } 228 228 … … 230 230 service_thread(struct workorder *work) 231 231 { 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 232 FILE *input, *output; 233 234 fprintf(stderr, "Start thread for connection %d.\n", work->conn); 235 236 ps(); 237 238 input = fdopen(work->conn, "r"); 239 if (input == NULL) { 240 oprogname(); 241 perror("can't create input stream"); 242 goto done; 243 } 244 245 output = fdopen(work->conn, "w"); 246 if (output == NULL) { 247 oprogname(); 248 perror("can't create output stream"); 249 fclose(input); 250 goto done; 251 } 252 253 setvbuf(input, NULL, _IONBF, 0); 254 setvbuf(output, NULL, _IONBF, 0); 255 256 run_interpreter(input, output); 257 258 fclose(input); 259 fclose(output); 260 260 261 261 done: 262 263 264 262 fprintf(stderr, "End thread for connection %d.\n", work->conn); 263 close(work->conn); 264 free(work); 265 265 } 266 266 … … 268 268 oprogname(void) 269 269 { 270 271 272 270 int save = errno; 271 fprintf(stderr, "%s: ", progname); 272 errno = save; 273 273 } 274 274 … … 276 276 run_interpreter(FILE *input, FILE *output) 277 277 { 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 278 PyThreadState *tstate; 279 PyObject *new_stdin, *new_stdout; 280 PyObject *mainmod, *globals; 281 char buffer[1000]; 282 char *p, *q; 283 int n, end; 284 285 PyEval_AcquireLock(); 286 tstate = Py_NewInterpreter(); 287 if (tstate == NULL) { 288 fprintf(output, "Sorry -- can't create an interpreter\n"); 289 return; 290 } 291 292 mainmod = PyImport_AddModule("__main__"); 293 globals = PyModule_GetDict(mainmod); 294 Py_INCREF(globals); 295 296 new_stdin = PyFile_FromFile(input, "<socket-in>", "r", NULL); 297 new_stdout = PyFile_FromFile(output, "<socket-out>", "w", NULL); 298 299 PySys_SetObject("stdin", new_stdin); 300 PySys_SetObject("stdout", new_stdout); 301 PySys_SetObject("stderr", new_stdout); 302 303 for (n = 1; !PyErr_Occurred(); n++) { 304 Py_BEGIN_ALLOW_THREADS 305 fprintf(output, "%d> ", n); 306 p = fgets(buffer, sizeof buffer, input); 307 Py_END_ALLOW_THREADS 308 309 if (p == NULL) 310 break; 311 if (p[0] == '\377' && p[1] == '\354') 312 break; 313 314 q = strrchr(p, '\r'); 315 if (q && q[1] == '\n' && q[2] == '\0') { 316 *q++ = '\n'; 317 *q++ = '\0'; 318 } 319 320 while (*p && isspace(*p)) 321 p++; 322 if (p[0] == '#' || p[0] == '\0') 323 continue; 324 325 end = run_command(buffer, globals); 326 if (end < 0) 327 PyErr_Print(); 328 329 if (end) 330 break; 331 } 332 333 Py_XDECREF(globals); 334 Py_XDECREF(new_stdin); 335 Py_XDECREF(new_stdout); 336 337 Py_EndInterpreter(tstate); 338 PyEval_ReleaseLock(); 339 340 fprintf(output, "Goodbye!\n"); 341 341 } 342 342 … … 344 344 run_command(char *buffer, PyObject *globals) 345 345 { 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 346 PyObject *m, *d, *v; 347 fprintf(stderr, "run_command: %s", buffer); 348 if (strchr(buffer, '\n') == NULL) 349 fprintf(stderr, "\n"); 350 v = PyRun_String(buffer, Py_single_input, globals, globals); 351 if (v == NULL) { 352 if (PyErr_Occurred() == PyExc_SystemExit) { 353 PyErr_Clear(); 354 return 1; 355 } 356 PyErr_Print(); 357 return 0; 358 } 359 Py_DECREF(v); 360 return 0; 361 361 } 362 362 … … 364 364 ps(void) 365 365 { 366 367 368 369 370 } 366 char buffer[100]; 367 PyOS_snprintf(buffer, sizeof(buffer), 368 "ps -l -p %d </dev/null | sed 1d\n", getpid()); 369 system(buffer); 370 } -
python/vendor/current/Demo/scripts/README
r2 r388 3 3 See also the Tools/scripts directory! 4 4 5 beer.py Print the classic 'bottles of beer' list .5 beer.py Print the classic 'bottles of beer' list 6 6 eqfix.py Fix .py files to use the correct equality test operator 7 7 fact.py Factorize numbers 8 find-uname.py Search for Unicode characters using regexps .8 find-uname.py Search for Unicode characters using regexps 9 9 from.py Summarize mailbox 10 ftpstats.py Summarize ftp daemon log file11 10 lpwatch.py Watch BSD line printer queues 12 11 makedir.py Like mkdir -p 13 12 markov.py Markov chain simulation of words or characters 14 mboxconvvert.py Convert MH or MMDF mailboxes to unix mailbox format 15 mkrcs.py Fix symlinks named RCS into parallel tree 13 mboxconvert.py Convert MH or MMDF mailboxes to unix mailbox format 16 14 morse.py Produce morse code (audible or on AIFF file) 15 newslist.py List all newsgroups on a NNTP server as HTML pages 17 16 pi.py Print all digits of pi -- given enough time and memory 18 17 pp.py Emulate some Perl command line options -
python/vendor/current/Demo/scripts/beer.py
r2 r388 1 1 #! /usr/bin/env python 2 2 3 # By GvR, demystified after a version by Fredrik Lundh. 4 3 5 import sys 6 4 7 n = 100 5 if sys.argv[1:]: n = int(sys.argv[1]) 8 if sys.argv[1:]: 9 n = int(sys.argv[1]) 10 6 11 def bottle(n): 7 12 if n == 0: return "no more bottles of beer" 8 13 if n == 1: return "one bottle of beer" 9 14 return str(n) + " bottles of beer" 10 for i in range(n): 11 print bottle(n-i), "on the wall," 12 print bottle(n-i) + "." 15 16 for i in range(n, 0, -1): 17 print bottle(i), "on the wall," 18 print bottle(i) + "." 13 19 print "Take one down, pass it around," 14 print bottle( n-i-1), "on the wall."20 print bottle(i-1), "on the wall." -
python/vendor/current/Demo/scripts/fact.py
r2 r388 10 10 11 11 def fact(n): 12 if n < 1: raise ValueError # fact() argument should be >= 1 13 if n == 1: return [] # special case 12 if n < 1: 13 raise ValueError('fact() argument should be >= 1') 14 if n == 1: 15 return [] # special case 14 16 res = [] 15 # Treat even factors special, so we can use i = i+2 later16 while n %2 == 0:17 # Treat even factors special, so we can use i += 2 later 18 while n % 2 == 0: 17 19 res.append(2) 18 n = n//220 n //= 2 19 21 # Try odd numbers up to sqrt(n) 20 limit = sqrt( float(n+1))22 limit = sqrt(n+1) 21 23 i = 3 22 24 while i <= limit: 23 if n %i == 0:25 if n % i == 0: 24 26 res.append(i) 25 n = n//i27 n //= i 26 28 limit = sqrt(n+1) 27 29 else: 28 i = i+230 i += 2 29 31 if n != 1: 30 32 res.append(n) … … 33 35 def main(): 34 36 if len(sys.argv) > 1: 35 for arg in sys.argv[1:]: 36 n = eval(arg) 37 source = sys.argv[1:] 38 else: 39 source = iter(raw_input, '') 40 for arg in source: 41 try: 42 n = int(arg) 43 except ValueError: 44 print arg, 'is not an integer' 45 else: 37 46 print n, fact(n) 38 else:39 try:40 while 1:41 n = input()42 print n, fact(n)43 except EOFError:44 pass45 47 46 48 if __name__ == "__main__": -
python/vendor/current/Demo/scripts/find-uname.py
r2 r388 22 22 23 23 def main(args): 24 unicode_names = []24 unicode_names = [] 25 25 for ix in range(sys.maxunicode+1): 26 26 try: 27 unicode_names.append( (ix, unicodedata.name(unichr(ix))))27 unicode_names.append((ix, unicodedata.name(unichr(ix)))) 28 28 except ValueError: # no name for the character 29 29 pass 30 30 for arg in args: 31 31 pat = re.compile(arg, re.I) 32 matches = [( x,y) for (x,y) in unicode_names33 32 matches = [(y,x) for (x,y) in unicode_names 33 if pat.search(y) is not None] 34 34 if matches: 35 35 print "***", arg, "matches", "***" 36 for (x,y)in matches:37 print "%s (%d)" % (y,x)36 for match in matches: 37 print "%s (%d)" % match 38 38 39 39 if __name__ == "__main__": -
python/vendor/current/Demo/scripts/lpwatch.py
r2 r388 4 4 # Intended for BSD 4.3 lpq. 5 5 6 import posix6 import os 7 7 import sys 8 8 import time 9 import string10 9 11 10 DEF_PRINTER = 'psc' … … 15 14 delay = DEF_DELAY # XXX Use getopt() later 16 15 try: 17 thisuser = posix.environ['LOGNAME']16 thisuser = os.environ['LOGNAME'] 18 17 except: 19 thisuser = posix.environ['USER']18 thisuser = os.environ['USER'] 20 19 printers = sys.argv[1:] 21 20 if printers: 22 21 # Strip '-P' from printer names just in case 23 22 # the user specified it... 24 for i in range(len(printers)):25 if printers[i][:2] == '-P':26 printers[i] = printers[i][2:]23 for i, name in enumerate(printers): 24 if name[:2] == '-P': 25 printers[i] = name[2:] 27 26 else: 28 if posix.environ.has_key('PRINTER'):29 printers = [ posix.environ['PRINTER']]27 if os.environ.has_key('PRINTER'): 28 printers = [os.environ['PRINTER']] 30 29 else: 31 30 printers = [DEF_PRINTER] 32 # 33 clearhome = posix.popen('clear', 'r').read()34 # 35 while 1:31 32 clearhome = os.popen('clear', 'r').read() 33 34 while True: 36 35 text = clearhome 37 36 for name in printers: 38 text = text +makestatus(name, thisuser) + '\n'37 text += makestatus(name, thisuser) + '\n' 39 38 print text 40 39 time.sleep(delay) 41 40 42 41 def makestatus(name, thisuser): 43 pipe = posix.popen('lpq -P' + name + ' 2>&1', 'r')42 pipe = os.popen('lpq -P' + name + ' 2>&1', 'r') 44 43 lines = [] 45 44 users = {} 46 45 aheadbytes = 0 47 46 aheadjobs = 0 48 userseen = 047 userseen = False 49 48 totalbytes = 0 50 49 totaljobs = 0 51 while 1: 52 line = pipe.readline() 53 if not line: break 54 fields = string.split(line) 50 for line in pipe: 51 fields = line.split() 55 52 n = len(fields) 56 53 if len(fields) >= 6 and fields[n-1] == 'bytes': 57 rank = fields[0] 58 user = fields[1] 59 job = fields[2] 54 rank, user, job = fields[0:3] 60 55 files = fields[3:-2] 61 bytes = eval(fields[n-2])56 bytes = int(fields[n-2]) 62 57 if user == thisuser: 63 userseen = 158 userseen = True 64 59 elif not userseen: 65 aheadbytes = aheadbytes + bytes 66 aheadjobs = aheadjobs + 1 67 totalbytes = totalbytes + bytes 68 totaljobs = totaljobs + 1 69 if users.has_key(user): 70 ujobs, ubytes = users[user] 71 else: 72 ujobs, ubytes = 0, 0 73 ujobs = ujobs + 1 74 ubytes = ubytes + bytes 60 aheadbytes += bytes 61 aheadjobs += 1 62 totalbytes += bytes 63 totaljobs += 1 64 ujobs, ubytes = users.get(user, (0, 0)) 65 ujobs += 1 66 ubytes += bytes 75 67 users[user] = ujobs, ubytes 76 68 else: 77 if fields and fields[0] <>'Rank':78 line = string.strip(line)69 if fields and fields[0] != 'Rank': 70 line = line.strip() 79 71 if line == 'no entries': 80 72 line = name + ': idle' … … 82 74 line = name 83 75 lines.append(line) 84 # 76 85 77 if totaljobs: 86 line = '%d K' % ((totalbytes+1023) //1024)87 if totaljobs <>len(users):88 line = line +' (%d jobs)' % totaljobs78 line = '%d K' % ((totalbytes+1023) // 1024) 79 if totaljobs != len(users): 80 line += ' (%d jobs)' % totaljobs 89 81 if len(users) == 1: 90 line = line +' for %s' % (users.keys()[0],)82 line += ' for %s' % (users.keys()[0],) 91 83 else: 92 line = line +' for %d users' % len(users)84 line += ' for %d users' % len(users) 93 85 if userseen: 94 86 if aheadjobs == 0: 95 line = line +' (%s first)' % thisuser87 line += ' (%s first)' % thisuser 96 88 else: 97 line = line +' (%d K before %s)' % (98 (aheadbytes+1023)//1024, thisuser)89 line += ' (%d K before %s)' % ( 90 (aheadbytes+1023) // 1024, thisuser) 99 91 lines.append(line) 100 # 92 101 93 sts = pipe.close() 102 94 if sts: 103 95 lines.append('lpq exit status %r' % (sts,)) 104 return string.joinfields(lines, ': ')96 return ': '.join(lines) 105 97 106 98 if __name__ == "__main__": -
python/vendor/current/Demo/scripts/markov.py
r2 r388 6 6 self.choice = choice 7 7 self.trans = {} 8 8 9 def add(self, state, next): 9 if not self.trans.has_key(state): 10 self.trans[state] = [next] 11 else: 12 self.trans[state].append(next) 10 self.trans.setdefault(state, []).append(next) 11 13 12 def put(self, seq): 14 13 n = self.histsize … … 18 17 add(seq[max(0, i-n):i], seq[i:i+1]) 19 18 add(seq[len(seq)-n:], None) 19 20 20 def get(self): 21 21 choice = self.choice … … 23 23 n = self.histsize 24 24 seq = choice(trans[None]) 25 while 1:25 while True: 26 26 subseq = seq[max(0, len(seq)-n):] 27 27 options = trans[subseq] 28 28 next = choice(options) 29 if not next: break 30 seq = seq + next 29 if not next: 30 break 31 seq += next 31 32 return seq 32 33 34 33 35 def test(): 34 import sys, string,random, getopt36 import sys, random, getopt 35 37 args = sys.argv[1:] 36 38 try: 37 opts, args = getopt.getopt(args, '0123456789cdw ')39 opts, args = getopt.getopt(args, '0123456789cdwq') 38 40 except getopt.error: 39 print 'Usage: markov [-#] [-cddqw] [file] ...'41 print 'Usage: %s [-#] [-cddqw] [file] ...' % sys.argv[0] 40 42 print 'Options:' 41 43 print '-#: 1-digit history size (default 2)' … … 50 52 print 'Output consists of paragraphs separated by blank' 51 53 print 'lines, where lines are no longer than 72 characters.' 54 sys.exit(2) 52 55 histsize = 2 53 do_words = 056 do_words = False 54 57 debug = 1 55 58 for o, a in opts: 56 if '-0' <= o <= '-9': histsize = eval(o[1:])57 if o == '-c': do_words = 058 if o == '-d': debug = debug +159 if '-0' <= o <= '-9': histsize = int(o[1:]) 60 if o == '-c': do_words = False 61 if o == '-d': debug += 1 59 62 if o == '-q': debug = 0 60 if o == '-w': do_words = 1 61 if not args: args = ['-'] 63 if o == '-w': do_words = True 64 if not args: 65 args = ['-'] 66 62 67 m = Markov(histsize, random.choice) 63 68 try: … … 73 78 text = f.read() 74 79 f.close() 75 paralist = string.splitfields(text,'\n\n')80 paralist = text.split('\n\n') 76 81 for para in paralist: 77 82 if debug > 1: print 'feeding ...' 78 words = string.split(para)83 words = para.split() 79 84 if words: 80 if do_words: data = tuple(words) 81 else: data = string.joinfields(words, ' ') 85 if do_words: 86 data = tuple(words) 87 else: 88 data = ' '.join(words) 82 89 m.put(data) 83 90 except KeyboardInterrupt: … … 87 94 return 88 95 if debug: print 'done.' 96 89 97 if debug > 1: 90 98 for key in m.trans.keys(): … … 93 101 if histsize == 0: print repr(''), m.trans[''] 94 102 print 95 while 1:103 while True: 96 104 data = m.get() 97 if do_words: words = data 98 else: words = string.split(data) 105 if do_words: 106 words = data 107 else: 108 words = data.split() 99 109 n = 0 100 110 limit = 72 … … 104 114 n = 0 105 115 print w, 106 n = n +len(w) + 1116 n += len(w) + 1 107 117 print 108 118 print 109 119 110 def tuple(list):111 if len(list) == 0: return ()112 if len(list) == 1: return (list[0],)113 i = len(list)//2114 return tuple(list[:i]) + tuple(list[i:])115 116 120 if __name__ == "__main__": 117 121 test() -
python/vendor/current/Demo/scripts/morse.py
r2 r388 1 #! /usr/bin/env python 2 1 3 # DAH should be three DOTs. 2 4 # Space between DOTs and DAHs should be one DOT. … … 37 39 'Y': '-.--', 'y': '-.--', 38 40 'Z': '--..', 'z': '--..', 39 '0': '-----', 40 '1': '.----', 41 '2': '..---', 42 '3': '...--', 43 '4': '....-', 44 '5': '.....', 45 '6': '-....', 46 '7': '--...', 47 '8': '---..', 48 '9': '----.', 49 ',': '--..--', 50 '.': '.-.-.-', 51 '?': '..--..', 52 ';': '-.-.-.', 53 ':': '---...', 54 "'": '.----.', 55 '-': '-....-', 56 '/': '-..-.', 57 '(': '-.--.-', 58 ')': '-.--.-', 59 '_': '..--.-', 60 ' ': ' ' 41 '0': '-----', ',': '--..--', 42 '1': '.----', '.': '.-.-.-', 43 '2': '..---', '?': '..--..', 44 '3': '...--', ';': '-.-.-.', 45 '4': '....-', ':': '---...', 46 '5': '.....', "'": '.----.', 47 '6': '-....', '-': '-....-', 48 '7': '--...', '/': '-..-.', 49 '8': '---..', '(': '-.--.-', 50 '9': '----.', ')': '-.--.-', 51 ' ': ' ', '_': '..--.-', 61 52 } 53 54 nowave = '\0' * 200 62 55 63 56 # If we play at 44.1 kHz (which we do), then if we produce one sine … … 66 59 # appears to be a nice one for playing morse code. 67 60 def mkwave(octave): 68 global sinewave, nowave69 61 sinewave = '' 70 62 for i in range(100): 71 val = int(math.sin(math.pi * float(i)* octave / 50.0) * 30000)72 sinewave = sinewave +chr((val >> 8) & 255) + chr(val & 255)73 nowave = '\0' * 20063 val = int(math.sin(math.pi * i * octave / 50.0) * 30000) 64 sinewave += chr((val >> 8) & 255) + chr(val & 255) 65 return sinewave 74 66 75 mkwave(OCTAVE)67 defaultwave = mkwave(OCTAVE) 76 68 77 69 def main(): 78 import getopt , string70 import getopt 79 71 try: 80 72 opts, args = getopt.getopt(sys.argv[1:], 'o:p:') 81 73 except getopt.error: 82 74 sys.stderr.write('Usage ' + sys.argv[0] + 83 ' [ -o outfile ] [ args ] ...\n')75 ' [ -o outfile ] [ -p octave ] [ words ] ...\n') 84 76 sys.exit(1) 85 77 dev = None 78 wave = defaultwave 86 79 for o, a in opts: 87 80 if o == '-o': … … 92 85 dev.setnchannels(1) 93 86 if o == '-p': 94 mkwave(string.atoi(a))87 wave = mkwave(int(a)) 95 88 if not dev: 96 89 import audiodev … … 102 95 dev.writeframesraw = dev.writeframes 103 96 if args: 104 line = string.join(args)97 source = [' '.join(args)] 105 98 else: 106 line = sys.stdin.readline()107 while line:99 source = iter(sys.stdin.readline, '') 100 for line in source: 108 101 mline = morse(line) 109 play(mline, dev )102 play(mline, dev, wave) 110 103 if hasattr(dev, 'wait'): 111 104 dev.wait() 112 if not args:113 line = sys.stdin.readline()114 else:115 line = ''116 105 dev.close() 117 106 … … 122 111 for c in line: 123 112 try: 124 res = res +morsetab[c] + '\001'113 res += morsetab[c] + '\001' 125 114 except KeyError: 126 115 pass … … 128 117 129 118 # Play a line of morse code. 130 def play(line, dev ):119 def play(line, dev, wave): 131 120 for c in line: 132 121 if c == '.': 133 sine(dev, DOT )122 sine(dev, DOT, wave) 134 123 elif c == '-': 135 sine(dev, DAH )124 sine(dev, DAH, wave) 136 125 else: # space 137 126 pause(dev, DAH + DOT) 138 127 pause(dev, DOT) 139 128 140 def sine(dev, length ):129 def sine(dev, length, wave): 141 130 for i in range(length): 142 dev.writeframesraw( sinewave)131 dev.writeframesraw(wave) 143 132 144 133 def pause(dev, length): … … 146 135 dev.writeframesraw(nowave) 147 136 148 if __name__ == '__main__' or sys.argv[0] == __name__:137 if __name__ == '__main__': 149 138 main() -
python/vendor/current/Demo/scripts/newslist.py
r2 r388 1 1 #! /usr/bin/env python 2 2 ####################################################################### 3 # Newslist $Revision : 66429$3 # Newslist $Revision$ 4 4 # 5 5 # Syntax: … … 33 33 # # 34 34 ####################################################################### 35 import sys, nntplib, string, marshal, time, os, posix, string35 import sys, nntplib, marshal, time, os 36 36 37 37 ####################################################################### … … 40 40 # Top directory. 41 41 # Filenames which don't start with / are taken as being relative to this. 42 topdir ='/anfs/qsbigdisc/web/html/newspage'42 topdir = os.path.expanduser('~/newspage') 43 43 44 44 # The name of your NNTP host … … 47 47 # or use following to get the name from the NNTPSERVER environment 48 48 # variable: 49 # newshost = posix.environ['NNTPSERVER']50 newshost = 'n ntp-serv.cl.cam.ac.uk'49 # newshost = os.environ['NNTPSERVER'] 50 newshost = 'news.example.com' 51 51 52 52 # The filename for a local cache of the newsgroup list … … 82 82 # further pages. This helps to make important links stand out. 83 83 # Set to '' if not wanted, or '...' is quite a good one. 84 pagelinkicon ='... <img src="http://pelican.cl.cam.ac.uk/icons/page.xbm"> '84 pagelinkicon = '... <img src="http://pelican.cl.cam.ac.uk/icons/page.xbm"> ' 85 85 86 86 # --------------------------------------------------------------------- … … 106 106 from stat import * 107 107 108 rcsrev = '$Revision : 66429$'109 rcsrev = string.join(filter(lambda s: '$' not in s, string.split(rcsrev)))108 rcsrev = '$Revision$' 109 rcsrev = ' '.join(filter(lambda s: '$' not in s, rcsrev.split())) 110 110 desc = {} 111 111 … … 121 121 print 'Updating tree...' 122 122 for i in groups: 123 parts = string.splitfields(i,'.')123 parts = i.split('.') 124 124 makeleaf(tree, parts) 125 125 … … 129 129 l = len(path) 130 130 131 if not tree.has_key(j):131 if j not in tree: 132 132 tree[j] = {} 133 133 if l == 1: … … 142 142 143 143 def createpage(root, tree, p): 144 filename = os.path.join(pagedir, root+'.html')144 filename = os.path.join(pagedir, root+'.html') 145 145 if root == rootpage: 146 146 detail = '' 147 147 else: 148 148 detail = ' under ' + root 149 f = open(filename,'w') 150 # f.write('Content-Type: text/html\n') 151 f.write('<TITLE>Newsgroups available' + detail + '</TITLE>\n') 152 f.write('<H1>Newsgroups available' + detail +'</H1>\n') 153 f.write('<A HREF="'+httppref+rootpage+'.html">Back to top level</A><P>\n') 154 printtree(f,tree,0,p) 155 f.write('<I>This page automatically created by \'newslist\' v. '+rcsrev+'.') 156 f.write(time.ctime(time.time()) + '</I><P>') 157 f.close() 149 with open(filename, 'w') as f: 150 # f.write('Content-Type: text/html\n') 151 f.write('<html>\n<head>\n') 152 f.write('<title>Newsgroups available%s</title>\n' % detail) 153 f.write('</head>\n<body>\n') 154 f.write('<h1>Newsgroups available%s</h1>\n' % detail) 155 f.write('<a href="%s%s.html">Back to top level</a><p>\n' % 156 (httppref, rootpage)) 157 printtree(f, tree, 0, p) 158 f.write('\n<p>') 159 f.write("<i>This page automatically created by 'newslist' v. %s." % 160 rcsrev) 161 f.write(time.ctime(time.time()) + '</i>\n') 162 f.write('</body>\n</html>\n') 158 163 159 164 # Printtree prints the groups as a bulleted list. Groups with … … 162 167 163 168 def printtree(f, tree, indent, p): 164 global desc165 169 l = len(tree) 166 170 167 if l > sublistsize and indent >0:171 if l > sublistsize and indent > 0: 168 172 # Create a new page and a link to it 169 f.write('< LI><B><A HREF="'+httppref+p[1:]+'.html">')170 f.write(p[1:] +'.*')171 f.write('</ A></B>'+pagelinkicon+'\n')173 f.write('<li><b><a href="%s%s.html">' % (httppref, p[1:])) 174 f.write(p[1:] + '.*') 175 f.write('</a></b>%s\n' % pagelinkicon) 172 176 createpage(p[1:], tree, p) 173 177 return … … 179 183 if indent > 0: 180 184 # Create a sub-list 181 f.write('< LI>'+p[1:]+'\n<UL>')185 f.write('<li>%s\n<ul>' % p[1:]) 182 186 else: 183 187 # Create a main list 184 f.write('< UL>')188 f.write('<ul>') 185 189 indent = indent + 1 186 190 … … 188 192 if i == '.': 189 193 # Output a newsgroup 190 f.write('< LI><A HREF="news:' + p[1:] + '">'+ p[1:] + '</A> ')191 if desc.has_key(p[1:]):192 f.write(' < I>'+desc[p[1:]]+'</I>\n')194 f.write('<li><a href="news:%s">%s</a> ' % (p[1:], p[1:])) 195 if p[1:] in desc: 196 f.write(' <i>%s</i>\n' % desc[p[1:]]) 193 197 else: 194 198 f.write('\n') 195 199 else: 196 200 # Output a hierarchy 197 printtree(f, tree[i], indent, p+'.'+i)201 printtree(f, tree[i], indent, p+'.'+i) 198 202 199 203 if l > 1: 200 f.write('\n</ UL>')204 f.write('\n</ul>') 201 205 202 206 # Reading descriptions file --------------------------------------- 203 207 204 # This returns a n arraymapping group name to its description208 # This returns a dict mapping group name to its description 205 209 206 210 def readdesc(descfile): 207 211 global desc 208 209 212 desc = {} 210 213 … … 213 216 214 217 try: 215 d = open(descfile, 'r') 216 print 'Reading descriptions...' 217 except (IOError): 218 with open(descfile, 'r') as d: 219 print 'Reading descriptions...' 220 for l in d: 221 bits = l.split() 222 try: 223 grp = bits[0] 224 dsc = ' '.join(bits[1:]) 225 if len(dsc) > 1: 226 desc[grp] = dsc 227 except IndexError: 228 pass 229 except IOError: 218 230 print 'Failed to open description file ' + descfile 219 231 return 220 l = d.readline()221 while l != '':222 bits = string.split(l)223 try:224 grp = bits[0]225 dsc = string.join(bits[1:])226 if len(dsc)>1:227 desc[grp] = dsc228 except (IndexError):229 pass230 l = d.readline()231 232 232 233 # Check that ouput directory exists, ------------------------------ … … 235 236 def checkopdir(pagedir): 236 237 if not os.path.isdir(pagedir): 237 print 'Directory '+pagedir+' does not exist.'238 print 'Directory %s does not exist.' % pagedir 238 239 print 'Shall I create it for you? (y/n)' 239 240 if sys.stdin.readline()[0] == 'y': 240 241 try: 241 os.mkdir(pagedir, 0777)242 os.mkdir(pagedir, 0777) 242 243 except: 243 244 print 'Sorry - failed!' … … 259 260 print 'use the -a option to create it.' 260 261 sys.exit(1) 261 treedate = '%02d%02d%02d' % (treetime[0] % 100 ,treetime[1], treetime[2]) 262 try: 263 dump = open(treefile,'r') 264 tree = marshal.load(dump) 265 dump.close() 266 except (IOError): 262 treedate = '%02d%02d%02d' % (treetime[0] % 100, treetime[1], treetime[2]) 263 try: 264 with open(treefile, 'rb') as dump: 265 tree = marshal.load(dump) 266 except IOError: 267 267 print 'Cannot open local group list ' + treefile 268 268 return (tree, treedate) … … 270 270 def writelocallist(treefile, tree): 271 271 try: 272 dump = open(treefile,'w') 273 groups = marshal.dump(tree,dump) 274 dump.close() 275 print 'Saved list to '+treefile+'\n' 272 with open(treefile, 'wb') as dump: 273 groups = marshal.dump(tree, dump) 274 print 'Saved list to %s\n' % treefile 276 275 except: 277 print 'Sorry - failed to write to local group cache '+treefile276 print 'Sorry - failed to write to local group cache', treefile 278 277 print 'Does it (or its directory) have the correct permissions?' 279 278 sys.exit(1) … … 283 282 def getallgroups(server): 284 283 print 'Getting list of all groups...' 285 treedate ='010101'284 treedate = '010101' 286 285 info = server.list()[1] 287 286 groups = [] … … 290 289 print '\nIgnoring following empty groups:' 291 290 for i in info: 292 grpname = string.split(i[0])[0]293 if skipempty and string.atoi(i[1]) < string.atoi(i[2]):294 print grpname +' ',291 grpname = i[0].split()[0] 292 if skipempty and int(i[1]) < int(i[2]): 293 print grpname + ' ', 295 294 else: 296 295 groups.append(grpname) … … 303 302 304 303 def getnewgroups(server, treedate): 305 print 'Getting list of new groups since start of '+treedate+'...',306 info = server.newgroups(treedate, '000001')[1]304 print 'Getting list of new groups since start of %s...' % treedate, 305 info = server.newgroups(treedate, '000001')[1] 307 306 print 'got %d.' % len(info) 308 307 print 'Processing...', 309 308 groups = [] 310 309 for i in info: 311 grpname = string.split(i)[0]310 grpname = i.split()[0] 312 311 groups.append(grpname) 313 312 print 'Done' … … 317 316 318 317 def main(): 319 global desc 320 321 tree={} 318 tree = {} 322 319 323 320 # Check that the output directory exists … … 325 322 326 323 try: 327 print 'Connecting to '+newshost+'...'324 print 'Connecting to %s...' % newshost 328 325 if sys.version[0] == '0': 329 326 s = NNTP.init(newshost) 330 327 else: 331 328 s = NNTP(newshost) 332 connected = 1329 connected = True 333 330 except (nntplib.error_temp, nntplib.error_perm), x: 334 331 print 'Error connecting to host:', x 335 332 print 'I\'ll try to use just the local list.' 336 connected = 0333 connected = False 337 334 338 335 # If -a is specified, read the full list of groups from server 339 336 if connected and len(sys.argv) > 1 and sys.argv[1] == '-a': 340 341 337 groups = getallgroups(s) 342 338 -
python/vendor/current/Demo/scripts/pi.py
r2 r388 12 12 13 13 def main(): 14 k, a, b, a1, b1 = 2 L, 4L, 1L, 12L, 4L15 while 1:14 k, a, b, a1, b1 = 2, 4, 1, 12, 4 15 while True: 16 16 # Next approximation 17 p, q, k = k*k, 2 L*k+1L, k+1L17 p, q, k = k*k, 2*k+1, k+1 18 18 a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1 19 19 # Print common digits … … 21 21 while d == d1: 22 22 output(d) 23 a, a1 = 10 L*(a%b), 10L*(a1%b1)23 a, a1 = 10*(a%b), 10*(a1%b1) 24 24 d, d1 = a//b, a1//b1 25 25 26 26 def output(d): 27 27 # Use write() to avoid spaces between the digits 28 # Use str() to avoid the 'L'29 28 sys.stdout.write(str(d)) 30 29 # Flush so the output is seen immediately -
python/vendor/current/Demo/scripts/pp.py
r2 r388 23 23 24 24 import sys 25 import string26 25 import getopt 27 26 … … 37 36 optlist, ARGS = getopt.getopt(sys.argv[1:], 'acde:F:np') 38 37 except getopt.error, msg: 39 sys.stderr.write( sys.argv[0] + ': ' + msg + '\n')38 sys.stderr.write('%s: %s\n' % (sys.argv[0], msg)) 40 39 sys.exit(2) 41 40 … … 48 47 DFLAG = 1 49 48 elif option == '-e': 50 for line in string.splitfields(optarg,'\n'):49 for line in optarg.split('\n'): 51 50 SCRIPT.append(line) 52 51 elif option == '-F': … … 82 81 # Note that it is on purpose that AFLAG and PFLAG are 83 82 # tested dynamically each time through the loop 84 prologue = [ \85 'LINECOUNT = 0', \86 'for FILE in ARGS:', \87 ' \tif FILE == \'-\':', \88 ' \t \tFP = sys.stdin', \89 ' \telse:', \90 ' \t \tFP = open(FILE, \'r\')', \91 ' \tLINENO = 0', \92 ' \twhile 1:', \93 ' \t \tLINE = FP.readline()', \94 ' \t \tif not LINE: break', \95 ' \t \tLINENO = LINENO + 1', \96 ' \t \tLINECOUNT = LINECOUNT + 1', \97 ' \t \tL = LINE[:-1]', \98 ' \t \taflag = AFLAG', \99 ' \t \tif aflag:', \100 ' \t \t \tif FS: F = string.splitfields(L, FS)', \101 ' \t \t \telse: F = string.split(L)' \83 prologue = [ 84 'LINECOUNT = 0', 85 'for FILE in ARGS:', 86 ' \tif FILE == \'-\':', 87 ' \t \tFP = sys.stdin', 88 ' \telse:', 89 ' \t \tFP = open(FILE, \'r\')', 90 ' \tLINENO = 0', 91 ' \twhile 1:', 92 ' \t \tLINE = FP.readline()', 93 ' \t \tif not LINE: break', 94 ' \t \tLINENO = LINENO + 1', 95 ' \t \tLINECOUNT = LINECOUNT + 1', 96 ' \t \tL = LINE[:-1]', 97 ' \t \taflag = AFLAG', 98 ' \t \tif aflag:', 99 ' \t \t \tif FS: F = L.split(FS)', 100 ' \t \t \telse: F = L.split()' 102 101 ] 103 epilogue = [ \104 ' \t \tif not PFLAG: continue', \105 ' \t \tif aflag:', \106 ' \t \t \tif FS: print string.joinfields(F, FS)', \107 ' \t \t \telse: print string.join(F)', \108 ' \t \telse: print L', \102 epilogue = [ 103 ' \t \tif not PFLAG: continue', 104 ' \t \tif aflag:', 105 ' \t \t \tif FS: print FS.join(F)', 106 ' \t \t \telse: print \' \'.join(F)', 107 ' \t \telse: print L', 109 108 ] 110 109 else: … … 115 114 # used in 'command' will come out right after re-indentation. 116 115 117 program = string.joinfields(prologue, '\n') + '\n'116 program = '\n'.join(prologue) + '\n' 118 117 for line in SCRIPT: 119 program = program + (' \t \t' + line + '\n')120 program = program + (string.joinfields(epilogue, '\n') + '\n')118 program += ' \t \t' + line + '\n' 119 program += '\n'.join(epilogue) + '\n' 121 120 122 121 import tempfile … … 126 125 if DFLAG: 127 126 import pdb 128 pdb.run('execfile(%r)' % ( tfn,))127 pdb.run('execfile(%r)' % (fp.name,)) 129 128 else: 130 execfile( tfn)129 execfile(fp.name) -
python/vendor/current/Demo/scripts/primes.py
r2 r388 2 2 3 3 # Print prime numbers in a given range 4 5 def primes(min, max): 6 if max >= 2 >= min: 7 print 2 8 primes = [2] 9 i = 3 10 while i <= max: 11 for p in primes: 12 if i % p == 0 or p*p > i: 13 break 14 if i % p != 0: 15 primes.append(i) 16 if i >= min: 17 print i 18 i += 2 4 19 5 20 def main(): … … 7 22 min, max = 2, 0x7fffffff 8 23 if sys.argv[1:]: 9 min = int( eval(sys.argv[1]))24 min = int(sys.argv[1]) 10 25 if sys.argv[2:]: 11 max = int( eval(sys.argv[2]))26 max = int(sys.argv[2]) 12 27 primes(min, max) 13 14 def primes(min, max):15 if 2 >= min: print 216 primes = [2]17 i = 318 while i <= max:19 for p in primes:20 if i%p == 0 or p*p > i: break21 if i%p <> 0:22 primes.append(i)23 if i >= min: print i24 i = i+225 28 26 29 if __name__ == "__main__": -
python/vendor/current/Demo/scripts/queens.py
r2 r388 20 20 def reset(self): 21 21 n = self.n 22 self.y = [None] *n# Where is the queen in column x23 self.row = [0] *n# Is row[y] safe?22 self.y = [None] * n # Where is the queen in column x 23 self.row = [0] * n # Is row[y] safe? 24 24 self.up = [0] * (2*n-1) # Is upward diagonal[x-y] safe? 25 25 self.down = [0] * (2*n-1) # Is downward diagonal[x+y] safe? … … 51 51 self.down[x+y] = 0 52 52 53 silent = 0 # If set, count solutions only53 silent = 0 # If true, count solutions only 54 54 55 55 def display(self): -
python/vendor/current/Demo/scripts/script.py
r2 r388 1 1 #! /usr/bin/env python 2 2 3 # script.py -- Make typescript of terminal session. 3 4 # Usage: … … 7 8 8 9 9 import os, time, sys 10 import os, time, sys, getopt 10 11 import pty 11 12 12 13 def read(fd): 13 14 data = os.read(fd, 1024) 14 file.write(data)15 script.write(data) 15 16 return data 16 17 … … 20 21 if os.environ.has_key('SHELL'): 21 22 shell = os.environ['SHELL'] 22 if '-a' in sys.argv:23 mode = 'a'24 if '-p' in sys.argv:25 shell = 'python'26 23 27 file = open(filename, mode) 24 try: 25 opts, args = getopt.getopt(sys.argv[1:], 'ap') 26 except getopt.error, msg: 27 print '%s: %s' % (sys.argv[0], msg) 28 sys.exit(2) 29 30 for o, a in opts: 31 if o == '-a': 32 mode = 'a' 33 elif o == '-p': 34 shell = 'python' 35 36 script = open(filename, mode) 28 37 29 38 sys.stdout.write('Script started, file is %s\n' % filename) 30 file.write('Script started on %s\n' % time.ctime(time.time()))39 script.write('Script started on %s\n' % time.ctime(time.time())) 31 40 pty.spawn(shell, read) 32 file.write('Script done on %s\n' % time.ctime(time.time()))41 script.write('Script done on %s\n' % time.ctime(time.time())) 33 42 sys.stdout.write('Script done, file is %s\n' % filename) -
python/vendor/current/Demo/scripts/unbirthday.py
r2 r388 11 11 12 12 def main(): 13 # Note that the range checks below also check for bad types,14 # e.g. 3.14 or (). However syntactically invalid replies15 # will raise an exception.16 13 if sys.argv[1:]: 17 14 year = int(sys.argv[1]) 18 15 else: 19 16 year = int(raw_input('In which year were you born? ')) 20 if 0 <=year<100:17 if 0 <= year < 100: 21 18 print "I'll assume that by", year, 22 19 year = year + 1900 23 20 print 'you mean', year, 'and not the early Christian era' 24 elif not (1850 <=year<=2002):21 elif not (1850 <= year <= time.localtime()[0]): 25 22 print "It's hard to believe you were born in", year 26 23 return 27 # 24 28 25 if sys.argv[2:]: 29 26 month = int(sys.argv[2]) 30 27 else: 31 28 month = int(raw_input('And in which month? (1-12) ')) 32 if not (1 <=month<=12):29 if not (1 <= month <= 12): 33 30 print 'There is no month numbered', month 34 31 return 35 # 32 36 33 if sys.argv[3:]: 37 34 day = int(sys.argv[3]) … … 42 39 else: 43 40 maxday = calendar.mdays[month] 44 if not (1 <=day<=maxday):41 if not (1 <= day <= maxday): 45 42 print 'There are no', day, 'days in that month!' 46 43 return 47 # 44 48 45 bdaytuple = (year, month, day) 49 46 bdaydate = mkdate(bdaytuple) 50 47 print 'You were born on', format(bdaytuple) 51 # 48 52 49 todaytuple = time.localtime()[:3] 53 50 todaydate = mkdate(todaytuple) 54 51 print 'Today is', format(todaytuple) 55 # 52 56 53 if bdaytuple > todaytuple: 57 54 print 'You are a time traveler. Go back to the future!' 58 55 return 59 # 56 60 57 if bdaytuple == todaytuple: 61 58 print 'You were born today. Have a nice life!' 62 59 return 63 # 60 64 61 days = todaydate - bdaydate 65 62 print 'You have lived', days, 'days' 66 # 63 67 64 age = 0 68 65 for y in range(year, todaytuple[0] + 1): 69 66 if bdaytuple < (y, month, day) <= todaytuple: 70 67 age = age + 1 71 # 68 72 69 print 'You are', age, 'years old' 73 # 70 74 71 if todaytuple[1:] == bdaytuple[1:]: 75 72 print 'Congratulations! Today is your', nth(age), 'birthday' … … 89 86 90 87 def mkdate((year, month, day)): 91 # Januar i1st, in 0 A.D. is arbitrarily defined to be day 1,88 # January 1st, in 0 A.D. is arbitrarily defined to be day 1, 92 89 # even though that day never actually existed and the calendar 93 90 # was different then... 94 days = year*365 # years, roughly91 days = year*365 # years, roughly 95 92 days = days + (year+3)//4 # plus leap years, roughly 96 93 days = days - (year+99)//100 # minus non-leap years every century -
python/vendor/current/Demo/sockets/README
r2 r388 6 6 ftp.py A very simple ftp client. 7 7 gopher.py A simple gopher client. 8 mcast.py IPv4/v6 multicast example 8 9 radio.py Receive time broadcasts from broadcast.py. 9 10 telnet.py Client for the 'telnet' protocol. … … 12 13 unixserver.py Unix socket example, server side 13 14 udpecho.py Client and server for the UDP echo protocol. 14 15 The following file is only relevant on SGI machines (or other systems16 that support multicast):17 18 mcast.py A Python translation of19 /usr/people/4Dgifts/examples/network/mcast.c20 (Note that IN.py is in ../../lib/sgi.)21 -
python/vendor/current/Demo/sockets/mcast.py
r2 r388 1 #!/usr/bin/env python 2 # 1 3 # Send/receive UDP multicast packets. 2 4 # Requires that your OS kernel supports IP multicast. 3 # This is built-in on SGI, still optional for most other vendors.4 5 # 5 6 # Usage: 6 # mcast -s (sender) 7 # mcast -b (sender, using broadcast instead multicast) 8 # mcast (receivers) 7 # mcast -s (sender, IPv4) 8 # mcast -s -6 (sender, IPv6) 9 # mcast (receivers, IPv4) 10 # mcast -6 (receivers, IPv6) 9 11 10 12 MYPORT = 8123 11 MYGROUP = '225.0.0.250' 13 MYGROUP_4 = '225.0.0.250' 14 MYGROUP_6 = 'ff15:7079:7468:6f6e:6465:6d6f:6d63:6173' 15 MYTTL = 1 # Increase to reach other networks 12 16 13 import sys14 17 import time 15 18 import struct 16 from socket import * 19 import socket 20 import sys 21 22 def main(): 23 group = MYGROUP_6 if "-6" in sys.argv[1:] else MYGROUP_4 24 25 if "-s" in sys.argv[1:]: 26 sender(group) 27 else: 28 receiver(group) 17 29 18 30 19 # Main program 20 def main(): 21 flags = sys.argv[1:] 22 # 23 if flags: 24 sender(flags[0]) 31 def sender(group): 32 addrinfo = socket.getaddrinfo(group, None)[0] 33 34 s = socket.socket(addrinfo[0], socket.SOCK_DGRAM) 35 36 # Set Time-to-live (optional) 37 ttl_bin = struct.pack('@i', MYTTL) 38 if addrinfo[0] == socket.AF_INET: # IPv4 39 s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin) 25 40 else: 26 receiver()41 s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, ttl_bin) 27 42 28 29 # Sender subroutine (only one per local area network) 30 def sender(flag): 31 s = socket(AF_INET, SOCK_DGRAM) 32 if flag == '-b': 33 s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) 34 mygroup = '<broadcast>' 35 else: 36 mygroup = MYGROUP 37 ttl = struct.pack('b', 1) # Time-to-live 38 s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl) 39 while 1: 43 while True: 40 44 data = repr(time.time()) 41 ## data = data + (1400 - len(data)) * '\0' 42 s.sendto(data, (mygroup, MYPORT)) 45 s.sendto(data + '\0', (addrinfo[4][0], MYPORT)) 43 46 time.sleep(1) 44 47 45 48 46 # Receiver subroutine (as many as you like) 47 def receiver(): 48 # Open and initialize the socket 49 s = openmcastsock(MYGROUP, MYPORT) 50 # 49 def receiver(group): 50 # Look up multicast group address in name server and find out IP version 51 addrinfo = socket.getaddrinfo(group, None)[0] 52 53 # Create a socket 54 s = socket.socket(addrinfo[0], socket.SOCK_DGRAM) 55 56 # Allow multiple copies of this program on one machine 57 # (not strictly needed) 58 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 59 60 # Bind it to the port 61 s.bind(('', MYPORT)) 62 63 group_bin = socket.inet_pton(addrinfo[0], addrinfo[4][0]) 64 # Join group 65 if addrinfo[0] == socket.AF_INET: # IPv4 66 mreq = group_bin + struct.pack('=I', socket.INADDR_ANY) 67 s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) 68 else: 69 mreq = group_bin + struct.pack('@I', 0) 70 s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq) 71 51 72 # Loop, printing any data we receive 52 while 1:73 while True: 53 74 data, sender = s.recvfrom(1500) 54 75 while data[-1:] == '\0': data = data[:-1] # Strip trailing \0's 55 print sender, ':', repr(data)76 print (str(sender) + ' ' + repr(data)) 56 77 57 78 58 # Open a UDP socket, bind it to a port and select a multicast group 59 def openmcastsock(group, port): 60 # Import modules used only here 61 import string 62 import struct 63 # 64 # Create a socket 65 s = socket(AF_INET, SOCK_DGRAM) 66 # 67 # Allow multiple copies of this program on one machine 68 # (not strictly needed) 69 s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) 70 # 71 # Bind it to the port 72 s.bind(('', port)) 73 # 74 # Look up multicast group address in name server 75 # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format) 76 group = gethostbyname(group) 77 # 78 # Construct binary group address 79 bytes = map(int, string.split(group, ".")) 80 grpaddr = 0 81 for byte in bytes: grpaddr = (grpaddr << 8) | byte 82 # 83 # Construct struct mreq from grpaddr and ifaddr 84 ifaddr = INADDR_ANY 85 mreq = struct.pack('ll', htonl(grpaddr), htonl(ifaddr)) 86 # 87 # Add group membership 88 s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) 89 # 90 return s 91 92 93 main() 79 if __name__ == '__main__': 80 main() -
python/vendor/current/Demo/threads/sync.py
r2 r388 266 266 # are allowed to proceed only if the current thread calls 267 267 # .read_out; threads waiting to read are only allowed to proceed 268 # if there are areno threads waiting to write. (This is a268 # if there are no threads waiting to write. (This is a 269 269 # weakness of the interface!) 270 270 -
python/vendor/current/Demo/tix/INSTALL.txt
r2 r388 1 $Id : INSTALL.txt 24230 2001-11-11 14:07:37Z loewis$1 $Id$ 2 2 3 3 Installing Tix.py -
python/vendor/current/Demo/tix/samples/Balloon.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : Balloon.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/samples/BtnBox.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : BtnBox.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/samples/CmpImg.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : CmpImg.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/samples/ComboBox.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : ComboBox.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/samples/Control.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : Control.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/samples/DirList.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : DirList.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/samples/DirTree.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : DirTree.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/samples/NoteBook.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : NoteBook.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/samples/OptMenu.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : OptMenu.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/samples/PanedWin.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : PanedWin.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/samples/PopMenu.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : PopMenu.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/samples/SHList1.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : SHList1.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/samples/SHList2.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : SHList2.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/samples/Tree.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : Tree.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # Tix Demostration Program -
python/vendor/current/Demo/tix/tixwidgets.py
r2 r388 1 1 # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- 2 2 # 3 # $Id : tixwidgets.py 36560 2004-07-18 06:16:08Z tim_one$3 # $Id$ 4 4 # 5 5 # tixwidgets.py -- … … 660 660 to glue together a bunch of bitmaps, images and text strings together 661 661 to form a bigger image. Then you can use this image with widgets that 662 support the -image option. For example, you can display a text string string662 support the -image option. For example, you can display a text string 663 663 together with a bitmap, at the same time, inside a TK button widget. 664 664 """) -
python/vendor/current/Demo/tkinter/README
r2 r388 9 9 guido my original example set (fairly random collection) 10 10 matt Matt Conway's examples, to go with his lifesaver document 11 ttk Examples using the ttk module -
python/vendor/current/Demo/turtle/about_turtle.txt
r2 r388 8 8 by Wally Feurzig and Seymour Papert in 1966. 9 9 10 Imagine a robotic turtle starting at (0, 0) in the x-y plane. Give it10 Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it 11 11 the command turtle.forward(15), and it moves (on-screen!) 15 pixels in 12 12 the direction it is facing, drawing a line as it moves. Give it the 13 command turtle. left(25), and it rotates in-place 25 degrees clockwise.13 command turtle.right(25), and it rotates in-place 25 degrees clockwise. 14 14 15 15 By combining together these and similar commands, intricate shapes and -
python/vendor/current/Demo/turtle/tdemo_I_dontlike_tiltdemo.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 """ turtle-example-suite: 3 3 -
python/vendor/current/Demo/turtle/tdemo_bytedesign.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 """ turtle-example-suite: 3 3 -
python/vendor/current/Demo/turtle/tdemo_clock.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 # -*- coding: cp1252 -*- 3 3 """ turtle-example-suite: -
python/vendor/current/Demo/turtle/tdemo_fractalcurves.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 """ turtle-example-suite: 3 3 -
python/vendor/current/Demo/turtle/tdemo_lindenmayer_indian.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 """ turtle-example-suite: 3 3 -
python/vendor/current/Demo/turtle/tdemo_minimal_hanoi.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 """ turtle-example-suite: 3 3 -
python/vendor/current/Demo/turtle/tdemo_paint.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 """ turtle-example-suite: 3 3 -
python/vendor/current/Demo/turtle/tdemo_peace.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 """ turtle-example-suite: 3 3 -
python/vendor/current/Demo/turtle/tdemo_penrose.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 """ xturtle-example-suite: 3 3 -
python/vendor/current/Demo/turtle/tdemo_planet_and_moon.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 """ turtle-example-suite: 3 3 -
python/vendor/current/Demo/turtle/tdemo_tree.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 """ turtle-example-suite: 3 3 -
python/vendor/current/Demo/turtle/tdemo_yinyang.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 """ turtle-example-suite: 3 3 -
python/vendor/current/Demo/turtle/turtleDemo.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 import sys 3 3 import os … … 213 213 self.text.insert("1.0",chars) 214 214 direc, fname = os.path.split(filename) 215 self.root.title(fname[6:-3]+" - a n xturtleexample")215 self.root.title(fname[6:-3]+" - a Python turtle graphics example") 216 216 self.module = __import__(fname[:-3]) 217 217 reload(self.module) -
python/vendor/current/Demo/turtle/turtledemo_two_canvases.py
r2 r388 1 #!/usr/bin/ python1 #!/usr/bin/env python 2 2 ## DEMONSTRATES USE OF 2 CANVASES, SO CANNOT BE RUN IN DEMOVIEWER! 3 3 """turtle example: Using TurtleScreen and RawTurtle -
python/vendor/current/Demo/xml/elem_count.py
r2 r388 1 """ 2 A simple demo that reads in an XML document and displays the number of 3 elements and attributes as well as a tally of elements and attributes by name. 4 """ 5 1 6 import sys 7 from collections import defaultdict 2 8 3 9 from xml.sax import make_parser, handler … … 8 14 self._elems = 0 9 15 self._attrs = 0 10 self._elem_types = {}11 self._attr_types = {}16 self._elem_types = defaultdict(int) 17 self._attr_types = defaultdict(int) 12 18 13 19 def startElement(self, name, attrs): 14 self._elems = self._elems +115 self._attrs = self._attrs +len(attrs)16 self._elem_types[name] = self._elem_types.get(name, 0) +120 self._elems += 1 21 self._attrs += len(attrs) 22 self._elem_types[name] += 1 17 23 18 24 for name in attrs.keys(): 19 self._attr_types[name] = self._attr_types.get(name, 0) +125 self._attr_types[name] += 1 20 26 21 27 def endDocument(self): … … 31 37 print "%20s %d" % pair 32 38 33 34 parser = make_parser()35 parser.setContentHandler(FancyCounter())36 parser.parse(sys.argv[1])39 if __name__ == '__main__': 40 parser = make_parser() 41 parser.setContentHandler(FancyCounter()) 42 parser.parse(sys.argv[1]) -
python/vendor/current/Demo/xml/roundtrip.py
r2 r388 4 4 """ 5 5 6 import sys , string6 import sys 7 7 8 8 from xml.sax import saxutils, handler, make_parser … … 12 12 class ContentGenerator(handler.ContentHandler): 13 13 14 def __init__(self, out =sys.stdout):14 def __init__(self, out=sys.stdout): 15 15 handler.ContentHandler.__init__(self) 16 16 self._out = out … … 41 41 # --- The main program 42 42 43 parser = make_parser() 44 parser.setContentHandler(ContentGenerator()) 45 parser.parse(sys.argv[1]) 43 if __name__ == '__main__': 44 parser = make_parser() 45 parser.setContentHandler(ContentGenerator()) 46 parser.parse(sys.argv[1]) -
python/vendor/current/Demo/xml/rss2html.py
r2 r388 1 """ 2 A demo that reads in an RSS XML document and emits an HTML file containing 3 a list of the individual items in the feed. 4 """ 5 1 6 import sys 7 import codecs 2 8 3 9 from xml.sax import make_parser, handler … … 5 11 # --- Templates 6 12 7 top = \ 8 """ 13 top = """\ 9 14 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 10 <HTML> 11 <HEAD> 12 <TITLE>%s</TITLE> 13 </HEAD> 15 <html> 16 <head> 17 <title>%s</title> 18 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 19 </head> 14 20 15 < BODY>16 < H1>%s</H1>21 <body> 22 <h1>%s</h1> 17 23 """ 18 24 19 bottom = \ 20 """ 25 bottom = """ 21 26 </ul> 22 27 23 < HR>24 < ADDRESS>25 Converted to HTML by sax_rss2html.py.26 </ ADDRESS>28 <hr> 29 <address> 30 Converted to HTML by rss2html.py. 31 </address> 27 32 28 </ BODY>29 </ HTML>33 </body> 34 </html> 30 35 """ 31 36 … … 34 39 class RSSHandler(handler.ContentHandler): 35 40 36 def __init__(self, out =sys.stdout):41 def __init__(self, out=sys.stdout): 37 42 handler.ContentHandler.__init__(self) 38 self._out = out43 self._out = codecs.getwriter('utf-8')(out) 39 44 40 45 self._text = "" 41 46 self._parent = None 42 self._list_started = 047 self._list_started = False 43 48 self._title = None 44 49 self._link = None … … 70 75 if not self._list_started: 71 76 self._out.write("<ul>\n") 72 self._list_started = 177 self._list_started = True 73 78 74 79 self._out.write(' <li><a href="%s">%s</a> %s\n' % … … 87 92 # --- Main program 88 93 89 parser = make_parser() 90 parser.setContentHandler(RSSHandler()) 91 parser.parse(sys.argv[1]) 94 if __name__ == '__main__': 95 parser = make_parser() 96 parser.setContentHandler(RSSHandler()) 97 parser.parse(sys.argv[1])
Note:
See TracChangeset
for help on using the changeset viewer.