Online Book Reader

Home Category

Learning Python - Mark Lutz [599]

By Root 1775 0

# Find the largest Python source file on the module import search path

import sys, os, pprint

visited = {}

allsizes = []

for srcdir in sys.path:

for (thisDir, subsHere, filesHere) in os.walk(srcdir):

thisDir = os.path.normpath(thisDir)

if thisDir.upper() in visited:

continue

else:

visited[thisDir.upper()] = True

for filename in filesHere:

if filename.endswith('.py'):

pypath = os.path.join(thisDir, filename)

try:

pysize = os.path.getsize(pypath)

except:

print('skipping', pypath)

allsizes.append((pysize, pypath))

allsizes.sort()

pprint.pprint(allsizes[:3])

pprint.pprint(allsizes[-3:])

# Sum columns in a text file separated by commas

filename = 'data.txt'

sums = {}

for line in open(filename):

cols = line.split(',')

nums = [int(col) for col in cols]

for (ix, num) in enumerate(nums):

sums[ix] = sums.get(ix, 0) + num

for key in sorted(sums):

print(key, '=', sums[key])

# Similar to prior, but using lists instead of dictionaries for sums

import sys

filename = sys.argv[1]

numcols = int(sys.argv[2])

totals = [0] * numcols

for line in open(filename):

cols = line.split(',')

nums = [int(x) for x in cols]

totals = [(x + y) for (x, y) in zip(totals, nums)]

print(totals)

# Test for regressions in the output of a set of scripts

import os

testscripts = [dict(script='test1.py', args=''), # Or glob script/args dir

dict(script='test2.py', args='spam')]

for testcase in testscripts:

commandline = '%(script)s %(args)s' % testcase

output = os.popen(commandline).read()

result = testcase['script'] + '.result'

if not os.path.exists(result):

open(result, 'w').write(output)

print('Created:', result)

else:

priorresult = open(result).read()

if output != priorresult:

print('FAILED:', testcase['script'])

print(output)

else:

print('Passed:', testcase['script'])

# Build GUI with tkinter (Tkinter in 2.6) with buttons that change color and grow

from tkinter import * # Use Tkinter in 2.6

import random

fontsize = 25

colors = ['red', 'green', 'blue', 'yellow', 'orange', 'white', 'cyan', 'purple']

def reply(text):

print(text)

popup = Toplevel()

color = random.choice(colors)

Label(popup, text='Popup', bg='black', fg=color).pack()

L.config(fg=color)

def timer():

L.config(fg=random.choice(colors))

win.after(250, timer)

def grow():

global fontsize

fontsize += 5

L.config(font=('arial', fontsize, 'italic'))

win.after(100, grow)

win = Tk()

L = Label(win, text='Spam',

font=('arial', fontsize, 'italic'), fg='yellow', bg='navy',

relief=RAISED)

L.pack(side=TOP, expand=YES, fill=BOTH)

Button(win, text='press', command=(lambda: reply('red'))).pack(side=BOTTOM,fill=X)

Button(win, text='timer', command=timer).pack(side=BOTTOM, fill=X)

Button(win, text='grow', command=grow).pack(side=BOTTOM, fill=X)

win.mainloop()

# Similar to prior, but use classes so each window has own state information

from tkinter import *

import random

class MyGui:

"""

A GUI with buttons that change color and make the label grow

"""

colors = ['blue', 'green', 'orange', 'red', 'brown', 'yellow']

def __init__(self, parent, title='popup'):

parent.title(title)

self.growing = False

self.fontsize = 10

self.lab = Label(parent, text='Gui1', fg='white', bg='navy')

self.lab.pack(expand=YES, fill=BOTH)

Button(parent, text='Spam', command=self.reply).pack(side=LEFT)

Button(parent, text='Grow', command=self.grow).pack(side=LEFT)

Button(parent, text='Stop', command=self.stop).pack(side=LEFT)

def reply(self):

"change the button's color at random on Spam presses"

self.fontsize += 5

color = random.choice(self.colors)

self.lab.config(bg=color,

font=('courier', self.fontsize, 'bold italic'))

def grow(self):

"start making the label grow on Grow presses"

self.growing = True

self.grower()

def grower(self):

if self.growing:

self.fontsize += 5

self.lab.config(font=('courier', self.fontsize, 'bold'))

self.lab.after(500, self.grower)

def stop(self):

"stop the button growing on Stop presses"

self.growing = False

class MySubGui(MyGui):

colors

Return Main Page Previous Page Next Page

®Online Book Reader