9-8
def moduledetail():
# dir(module)
module = raw_input('your module name: ')
exec 'import ' + module
alist = dir(eval(module))
# print dir(module)
length = len(alist) + 3
start = 0
for i in range(3, length, 3):
print alist[start:i]
start += 3
# print the detail of a method or attribute
methodorattribute = raw_input('which method or attribute: ')
print 'name: ', methodorattribute
print 'type: ', type(eval(module+'.'+methodorattribute))
print 'id number: ', id(eval(module+'.'+methodorattribute))
print 'value: ', getattr(eval(module), methodorattribute)
moduledetail()
9-9
import os
import os.path
nodoc = []
def modulestudy():
os.chdir('c:\\Python27\\Lib')
print os.getcwd()
alist = [i for i in os.listdir('.') if os.path.splitext(i)[1] == '.py']
# remove some useless file
alist.remove('pty.py') # only be used in Unix
alist.remove('tty.py') # only be used in Unix
alist.remove('antigravity.py') # open a website
alist.remove('this.py') # open 'The Zen of Python'
alist.remove('__phello__.foo.py') # only a file
print alist, os.path.splitext('__phello__.foo.py')
for i in alist:
module = os.path.splitext(i)[0]
exec 'import ' + module
# screen the module
if eval(module+'.__doc__') is None:
nodoc.append(module)
else:
print module,
# print
# exec 'print ' + module + '.__doc__'
print
print 'the module that do not have docstring: ', nodoc
modulestudy()
9-12(a)
def storedata():
f = open('data.txt', 'w')
data = db.iteritems()
for name, pair in data:
f.write(name+': '+pair[0]+': '+str(pair[1])+'\n')
f.close()
9-12(b)
def storedata():
import pickle
output = open('data.pkl', 'wb')
pickle.dump(db, output)
output.close()
9-12(c)
def storedata():
import shelve
d = shelve.open('data')
d[all] = db
d.close()
9-13
import sys
print str(sys.argv)
9-14
import shelve
from sys import argv
def calculate():
script, expression = argv
if expression == 'print':
f = shelve.open('cal.txt')
for i in f:
print i
print f[i]
f.clear()
f.close()
else:
for i in ['**', '+', '-', '*', '/', '%']:
if i in expression:
x = expression.split(i)
break
else:
print 'a wrong operator'
for j in range(2):
if '.' in x[j]:
x[j] = float(x[j])
else:
x[j] = int(x[j])
calcudict = {'+': x[0] + x[1], '-': x[0] - x[1], '*': x[0] * x[1],
'/': x[0] / x[1], '**': x[0] ** x[1], '%': x[0] % x[1]}
print calcudict[i]
f = shelve.open('cal.txt')
f[expression] = calcudict[i]
f.close()
calculate()