Changeset 388 for python/vendor/current/Demo/scripts
- Timestamp:
- Mar 19, 2014, 11:11:30 AM (11 years ago)
- Location:
- python/vendor/current/Demo/scripts
- Files:
-
- 3 deleted
- 14 edited
Legend:
- Unmodified
- Added
- Removed
-
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
Note:
See TracChangeset
for help on using the changeset viewer.