Differences between revisions 9 and 34 (spanning 25 versions)
Revision 9 as of 2008-04-27 01:15:37
Size: 25067
Editor: lizzie
Comment:
Revision 34 as of 2008-10-06 08:48:22
Size: 813
Editor: ZoomQuiet
Comment:
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
## page was renamed from ObpLovelyPython/LpyAttach-answer
## page was renamed from ObpLovelyPython/Answer
Line 2: Line 4:
#pragma section-numbers on #pragma section-numbers off
Line 4: Line 6:
||'''status''' || 校对 || ShengYan || 完成度70% ||
[[TableOfContents]]
||'''status''' || 校对 || lizzie || 完成度100% ||
[[TableOfContents(2)]]
Line 7: Line 9:
## 编辑正文收集在:
### http://openbookproject.googlecode.com/svn/trunk/LovelyPython/exercise/part2-KDays/LpyAttach3answer-KDays.moin
### http://openbookproject.googlecode.com/svn/trunk/LovelyPython/exercise/part1-CDays/LpyAttach3answer-CDays.moin

##startInc
Line 8: Line 15:
== CDays ==
=== CDays-5 ===
 * 计算今年是闰年嘛?
  . 相关代码:
{{{
#!python
#coding:utf-8
'''cdays-5-exercise-1.py this year is a leap year or not
'''
#导入time模块
import time
#获取当前年份
thisyear = time.localtime()[0]
#判断闰年条件,满足模400为0,或者模4为0但模100不为0
if thisyear % 400 == 0 or thisyear % 4 ==0 and thisyear % 100 <> 0:
        print 'this year %s is a leap year' % thisyear
else:
        print 'this year %s is not a leap year' % thisyear
}}}
 * 利用python作为科学计算器。熟悉Python中的常用运算符,并分别求出表达式12*34+78-132/6、(12*(34+78)-132)/6、(8.6/4)**5的值。并利用`math`模块进行数学计算,分别求出145/23的余数,0.5的sin和cos值等等,详细可参考help(math)。
  . 相关代码:
{{{
#!python
#coding:utf-8
'''cdays-5-exercise-2.py basic operation and math library
'''
#表达式计算
x = 12*34+78-132/6
y = (12*(34+78)-132)/6
z = (8.6/4)**5
print '12*34+78-132/6 = %d' % x
print '(12*(34+78)-132)/6 = %d' % y
print '(8.6/4)**5 = %f' % z
#导入数学计算模块
import math
#求余函数
a = math.fmod(145, 23)
#正弦函数
b = math.sin(0.5)
#余弦函数
c = math.cos(0.5)
print '145/23的余数 = %d' % a
print 'sin(0.5) = %f' %b
print 'cos(0.5) = %f' %c
}}}
 * 编写程序,在屏幕上打印出如下图案:
attachment:cdays-5-exercise-3.png
Line 56: Line 16:
 . 相关代码:
{{{
#!python
#coding:utf-8
'''cdays-5-exercise-3.py print out and for expression
'''
for index in range(1, 6):
        if index > 3:
                #调整index
                index = 2*3 -index
        #输出每行空格个数
        print ' '*(3-index),
        #输出每行*的个数
        print '*'*(2*index - 1)
}}}
截图
== CDays 故事解答 ==
[[Include(/CDays,,from="^##startInc",to="^##endInc")]]
Line 73: Line 19:
=== CDays-4 ===
 * os 模块中还有哪些功能可以使用? -- 提示使用 `dir()` `help()`
  1. os.error, os.path, os.popen, os.stat_result, os.sys, os.system等等等
  1. 详细可参见`dir(os)`和python帮助文档`help(os)`
 * `open()` 还有哪些模式可以使用?
  1. 'r': 以只读方式打开已存在文件,若文件不存在则抛出异常。此方式是默认方式
  1. 'U'或者'rU': python惯例构造了通用换行支持;提供'U'模式以文本方式打开一个文件,但是行可能随时结束:Unix的结束符规定为'\n',苹果系统则为'\r',还有windows规定为'\r\n',所有这些规定在python程序中统一为'\n'.如果python不构造一个通用换行支持模式'u'来用统一对待正常文本模式的话
  1. 'w': 以可写方式打开存在或者不存在的文件,若文件不存在则先新建该文件,若文件存在则覆盖该文件
  1. 'a': 用于追加,对unix系统而言,所有的内容都将追加到文件末尾而不管指针的当前位置如何
  1. 'b': 以二进制方式打开。打开一个二进制文件必须用该模式。增加'b'模式是用来兼容系统对当二进制和文本文件的处理不同
  1. 'r+','w+'和'a+'以更新方式打开文件(注意'w+'覆盖文件)
 * 尝试`for .. in ..` 循环可以对哪些数据类型进行操作?
  1. for..in循环对于任何序列(列表,元组,字符串)都适用。但从广义说来可以使用任何种类的由任何对象组成的序列
 * 格式化声明,还有哪些格式可以进行约定?
  详细参考:[http://docs.python.org/lib/typesseq-strings.html typesseq-strings]
  1. d Signed integer decimal.
  1. i Signed integer decimal.
  1. o Unsigned octal.
  1. u Unsigned decimal.
  1. x Unsigned hexadecimal (lowercase).
  1. X Unsigned hexadecimal (uppercase).
  1. e Floating point exponential format (lowercase).
  1. E Floating point exponential format (uppercase).
  1. f Floating point decimal format.
  1. F Floating point decimal format.
  1. g Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise.
  1. G Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise.
  1. c Single character (accepts integer or single character string).
  1. r String (converts any python object using repr()).
  1. s String (converts any python object using str()).
  1. % No argument is converted, results in a "%" character in the result.
== KDays 故事解答 ==
[[Include(/KDays,,from="^##startInc",to="^##endInc")]]
Line 105: Line 22:
 * 现在的写入文件模式好嘛? 有改进的余地?
'''CDay-4-5.py''' 好在哪里? :

{{{
#!python
# coding : utf-8
import os
export = ""
for root, dirs, files in os.walk('/media/cdrom0'):
  export+="\n %s;%s;%s" % (root,dirs,files)
open('mycd2.cdc', 'w').write(export)
}}}
'''CDay-4-6.py''' 又更加好在哪里? :

{{{
#!python
# coding : utf-8
import os
export = []
for root, dirs, files in os.walk('/media/cdrom0'):
    export.append("\n %s;%s;%s" % (root,dirs,files))
open('mycd2.cdc', 'w').write(''.join(export))
}}}
    1. CDay-4-5.py中使用了字符串的`+`连接,而CDay-4-6.py中是利用`join`。字符串的join要比'+'操作效率高。因为对象的反复+,比一次性内建处理,要浪费更多的资源。

 * 读取文件cdays-4-test.txt内容,去除空行和注释行后,以行为单位进行排序,并将结果输出为cdays-4-result.txt。
{{{
#!python
#coding:utf-8
'''cdays-4-exercise-6.py file operation
'''
#以读方式打开文件
f = open('cdays-4-test.txt', 'r')
result = list()
#依次读取每行
for line in f.readlines():
        #去掉每行头尾空白
 line = line.strip()
        #判断是否是空行或注释行
 if not len(line) or line.startswith('#'):
                #是的话,跳过不处理
  continue
 result.append(line)
#排序结果
result.sort()
#保存入结果文件
open('cdays-4-result.txt', 'w').write('%s' % '\n'.join(result))
}}}
=== CDays-3 ===
 * 根据 [http://www.woodpecker.org.cn/diveintopython/scripts_and_streams/command_line_arguments.html DiPy 10.6. 处理命令行参数] 使用`getopt.getopt()` 优化当前功能函式。
{{{
#!python
# coding=utf-8
'''Lovely Python -3 PyDay
    PyCDC v0.3
'''
import os,sys
import getopt

CDROM = '/media/cdrom0'
def cdWalker(cdrom,cdcfile):
 export = ""
 for root, dirs, files in os.walk(cdrom):
  export+="\n %s;%s;%s" % (root,dirs,files)
 open(cdcfile, 'w').write(export)

def usage():
 print '''PyCDC 使用方式:
 python cdays-3-exercise-1.py -d cdc -k 中国火
 #搜索 cdc 目录中的光盘信息,寻找有“中国火”字样的文件或是目录,在哪张光盘中
        '''

try:
 opts, args = getopt.getopt(sys.argv[1:], 'hd:e:k:')
except getopt.GetoptError:
 usage()
 sys.exit()

if len(opts) == 0:
 usage()
 sys.exit()

c_path = ''
for opt, arg in opts:
 if opt in ('-h', '--help'):
  usage()
  sys.exit()
 elif opt == '-e':
  #判别sys.argv[2]中是否有目录,以便进行自动创建
  #cdWalker(CDROM, arg)
  print "记录光盘信息到 %s" % arg
 elif opt == '-d':
  c_path = arg
 elif opt == '-k':
  if not c_path:
   usage()
   sys.exit()
  #进行文件搜索

}}}
 * 读取某一简单索引文件cdays-3-test.txt,其每行格式为文档序号 关键词,现需根据这些信息转化为倒排索引,即统计关键词在哪些文档中,格式如下:包含该关键词的文档数 关键词 => 文档序号。其中,原索引文件作为命令行参数传入主程序,并设计一个collect函数统计关键字-序号结果对,最后在主程序中输出结果至屏幕。
{{{
#!python
#coding:utf-8
'''cdays-3-exercise-2.py using sys.args, dict and function invoke
'''
#导入sys模块
import sys

def collect(file):
 ''' function collect: change the key-value to value-key
 @param file: file object
 @return: a dict type, get the value-key pairs
 '''
 result = {}
        #依次读取每行
 for line in file.readlines():
  #将一行以空格分割为左右两部分
  left, right = line.split()
  #判断是否已经含有right值对应的key
  if result.has_key(right):
   #若有,直接添加到result[right]的值列表
   result[right].append(left)
  else:
                        #没有,则新建result[right]的值列表
   result[right] = [left]
 return result

if __name__ == "__main__":
        #判断参数个数
 if len(sys.argv) == 1:
  print 'usage:\n\tpython cdays-3-exercise-2.py cdays-3-test.txt'
 else:
                #调用collect函数,返回结果
  result = collect(open(sys.argv[1], 'r'))
                #输出结果
  for (right, lefts) in result.items():
   print "%d '%s'\t=>\t%s" % (len(lefts), right, lefts)
}}}
 * 八皇后问题。在8*8的棋盘上,放置8个皇后,使得任两个皇后不在同行同列同正负对角线上。
{{{
#!python
#coding:utf-8
'''cdays-3-exercise-3.py using global varibles, invoke function recursively
'''
#定义一些全局变量
global col
global row
global pos_diag
global nag_diag
global count

def output():
 ''' function output: print out one state
 '''
 global count
 print row
 count += 1

def do_queen(i):
 ''' function do_queen: generate all states of queens' position
 @param i: the number of queen
 '''
        #依次尝试0~7位置
 for j in range(0, 8):
  #若该行,正对角线,负对角线上都没有皇后,则放入i皇后
  if col[j] == 1 and pos_diag[i-j+7] == 1 and nag_diag[i+j] == 1:
   row[i] = j
   #调整各个列表状态
   col[j] = 0
   pos_diag[i-j+7] = 0
   nag_diag[i+j] = 0
   if i < 7:
    #可递增或递减
    do_queen(i+1)
   else:
    #产生一个结果,输出
    output()
   #恢复各个列表状态为之前的
   col[j] = 1
   pos_diag[i-j+7] = 1
   nag_diag[i+j] = 1

if __name__ == '__main__':
 #矩阵列的列表,存储皇后所在列,若该列有皇后,则相应置为1,反之则0
 col = []
 #矩阵行的列表,存放每行皇后所在的位置,随着程序的执行,在不断的变化中,之间输出结果
 row = []
 #正对角线,i-j恒定,-7~0~7,并且b(i)+7统一到0~14
 pos_diag = []
 #负对角线,i+j恒定,0~14
 nag_diag = []
 count = 0
        #一些初始化工作
 for index in range(0, 8):
  col.append(1)
  row.append(0)
 for index in range(0, 15):
  pos_diag.append(1)
  nag_diag.append(1)
        #开始递归,先放一个,依次递增,反过来,从7开始递减也可
 do_queen(0)
 print 'Totally have %d solutions!' % count

}}}
=== CDays-2 ===
 * 把最后探索出的 `cdcGrep()`嵌入 pycdc-v0.5.py 实现完成版本的 PyCDC
{{{
#!python
# coding= utf-8
'''pycdc-v0.5.py
Lovely Python -2 PyDay
'''
import sys, cmd
from cdctools import *
class PyCDC(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self) # initialize the base class
        self.CDROM = '/media/cdrom0'
        self.CDDIR = 'cdc/'
        self.prompt="(PyCDC)>"
        self.intro = '''PyCDC0.5 使用说明:
    dir 目录名 #指定保存和搜索目录,默认是 "cdc"
    walk 文件名 #指定光盘信息文件名,使用 "*.cdc"
    find 关键词 #遍历搜索目录中所有.cdc文件,输出含有关键词的行
    ? # 查询
    EOF # 退出系统,也可以使用Crtl+D(Unix)|Ctrl+Z(dos/windows)
        '''

    def help_EOF(self):
        print "退出程序 Quits the program"
    def do_EOF(self, line):
        sys.exit()

    def help_walk(self):
        print "扫描光盘内容 walk cd and export into *.cdc"
    def do_walk(self, filename):
        if filename == "":filename = raw_input("输入cdc文件名:: ")
        print "扫描光盘内容保存到:'%s'" % filename
        cdWalker(self.CDROM,self.CDDIR+filename)

    def help_dir(self):
        print "指定保存/搜索目录"
    def do_dir(self, pathname):
        if pathname == "": pathname = raw_input("输入指定保存/搜索目录: ")
        self.CDDIR = pathname
        print "指定保存/搜索目录:'%s' ;默认是:'%s'" % (pathname,self.CDDIR)

    def help_find(self):
        print "搜索关键词"
    def do_find(self, keyword):
        if keyword == "": keyword = raw_input("输入搜索关键字: ")
        print "搜索关键词:'%s'" % keyword
        cdcGrep(self.CDDIR,keyword)

if __name__ == '__main__': # this way the module can be
    cdc = PyCDC() # imported by other programs as well
    cdc.cmdloop()
}}}
 * 编写一个类,实现简单的栈。数据的操作按照先进后出(FILO)的顺序。主要成员函数为put(item),实现数据item插入栈中;get(),实现从栈中取一个数据。
{{{
#!python
#coding:utf-8
'''cdays-2-exercise-2.py using class and object
'''

class MyStack(object):
 '''MyStack
  user-defined stack, has basic stack operations, such as put(), get() and isEmpty()
 '''
 def __init__(self, max):
  '''
  init the stack: the head of stack and empty the stack
  @param max: specify the max length of stack
  '''
  self.head = -1
  self.stack = list()
  self.max = max
  for i in range(self.max):
   self.stack.append(0)
 
 def put(self, item):
  '''
  put item into the stack
  @param item: anything want to put the current stack
  '''
  if self.head >= self.max:#判断当前栈是否满了
   return 'Put Error: The Stack is Overflow!'#提示栈溢出
  else:
   self.head += 1#不满,则将item入栈,调整栈顶指针
   self.stack[self.head] = item
 
 def get(self):
  '''
  get the top item of current stack
  @return: the top item
  '''
  if self.head < 0:#判断当前栈是否为空
   return 'Get Error: The Stack is Empty!' #提示栈空
  else:
   self.head -= 1 #出栈,返回栈顶元素,并调整栈顶指针
   return self.stack[self.head+1]
 
 def isEmpty(self):
  '''
  get the state of current stack
  @return: True(the stack is empty) or False(else)
  '''
  if self.head < -1:
   return True
  return False

if __name__ == "__main__":
 mystack = MyStack(100)
 mystack.put('a')
 mystack.put('b')
 print mystack.get()
 mystack.put('c')
 print mystack.get()
 print mystack.get()
 print mystack.get()

}}}
=== CDays-1 ===
 * 自动判定你自个儿的Blog 是什么编码的?
{{{
#!python
#coding:utf-8
'''cdays-1-exercise-1.py using chardet and urllib2
'''

import sys
import urllib2
import chardet

def blog_detect(blogurl):
 '''
 detect the coding of blog
 @param blogurl: some url string
 '''
 try:
  fp = urllib2.urlopen(blogurl)#尝试打开给定url
 except Exception, e:#若产生异常,则给出相关提示并返回
  print e
  print 'download exception %s' % blogurl
  return 0
 blog = fp.read()#读取内容
 codedetect = chardet.detect(blog)["encoding"]#检测得到编码方式
 print '%s\t<-\t%s' % (blogurl, codedetect)
 fp.close()#关闭
 return 1
    
if __name__ == "__main__":
 if len(sys.argv) == 1:
  print 'usage:\n\tpython cdays-1-exercise-1.py http://xxxx.com'
 else:
  blog_detect(sys.argv[1])

}}}
 * 在题一基础上,如果blog的编码不是utf-8,编写小程序自动将其转换成utf-8 编码保存到本地?
{{{
#!python
#coding:utf-8
'''cdays-1-exercise-2.py using chardet, urllib2
'''
import sys
import urllib2
import chardet

def blog_detect(blogurl):
 '''
 detect the coding of blog and save the blog in utf-8
 @param blogurl: some url string
 '''
 try:
  fp = urllib2.urlopen(blogurl)#尝试打开给定url
 except Exception, e:#若产生异常,则给出相关提示并返回
  print e
  print 'download exception %s' % blogurl
  return 0
 blog = fp.read()#读取内容
 fp.close()#关闭
 codedetect = chardet.detect(blog)["encoding"]#检测得到编码方式
 if codedetect <> 'utf-8':#是否是utf-8
  try:
   blog = unicode(blog, codedetect) #不是的话,则尝试转换
   blog = blog.encode('utf8')
  except:
   print u"bad unicode encode try!"
   return 0
 filename = '%s_utf-8' % blogurl[7:]#保存入文件
 filename = filename.replace('/', '_')
 open(filename, 'w').write('%s' % blog)
 print 'save to file %s' % filename
 return 1
    
if __name__ == "__main__":
 if len(sys.argv) == 1:
  print 'usage:\n\tpython cdays-1-exercise-2.py http://xxxx.com'
 else:
  blog_detect(sys.argv[1])

}}}
=== CDays-0 ===
 * 请根据软件发布的流程和软件开发的编码规范,将读者之前章节写的程序修改并发布出去。另外,可以查找下除了epydoc外还有哪些较好的py文档生成器?
   步骤:
   1. 编写epydoc的配置文件,如下cdays0-epydoc.cfg。
   1. 在终端中输入epydoc --config cdays0-epydoc.cfg,即可生成文档。
{{{
[epydoc]
# Epydoc section marker (required by ConfigParser)

# Information about the project.
name: MyStack
url: http://wiki.woodpecker.org.cn/moin/ObpLovelyPython

# The list of modules to document. Modules can be named using
# dotted names, module filenames, or package directory names.
# This option may be repeated.
modules: ./cdays0-exercise-1.py

# Write html output to the directory "apidocs"
output: html
target: apidocs/

# Include all automatically generated graphs. These graphs are
# generated using Graphviz dot.
graph: all
dotpath: /usr/bin/dot
}}}

=== CDays+1 ===
 * 编程实现以下功能并进行最大化的优化:遍历指定目录下的所有文件,找出其中占用空间最大的前3个文件。
{{{
#!python
#coding:utf-8
'''cdays+1-exercise-1.py using os.stat
'''
import sys
import os

def get_top_three(path):
 ''' get the three big size of files in the path
 @param path: specify the files of path
 @return one list contains item like (size, filename)
 '''
 all_file = {}
 for root, dirs, files in os.walk(path):#遍历path
  for onefile in files:
   fname = os.path.join(root, onefile)#获得当前处理文件的完整名字
   fsize = os.stat(fname).st_size#获得当前处理文件大小
   if all_file.has_key(fsize):#按照文件大小存储
    all_file[fsize].append(fname)
   else:
    all_file[fsize] = [fname]
 fsize_key = all_file.keys()#得到所有的文件大小
 fsize_key.sort()#排序,从小到大
 result = []
 for i in [-1, -2, -3]:#依次取最大的三个
  for j in all_file[fsize_key[i]]:#保存
   result.append((fsize_key[i], j))
 return result[:3]#返回前三个
    
if __name__ == "__main__":
 if len(sys.argv) == 1:
  print 'usage:\n\tpython cdays+1-exercise-1.py path'
 else:
  abs_path = os.path.abspath(sys.argv[1])#得到绝对路径
  if not os.path.isdir(abs_path): #判断所给的路径是否存在
   print '%s is not exist' % abs_path
  else:
   top = get_top_three(abs_path)
   for (s, f) in top:
    print '%s\t->\t%s' % (s, f)
}}}
 * 利用ConfigParser,将上述题目中产生的结果按照cdays+1-my.ini格式存储到文件cdays+1-result.txt中。
{{{
#!python
#coding:utf-8
'''cdays+1-exercise-2.py using ConfigParser
'''
import os
import sys
from ConfigParser import RawConfigParser

def iniTT(size_file):
 ''' 按照.ini的格式,存储size_file
 '''
 cfg = RawConfigParser()
 print size_file
 index = 1
 for (s, f) in size_file:
  cfg.add_section("%d" % index)#增加一个section
  cfg.set("%d" % index, 'Filename', f)#在该section设置Filename及其值
  cfg.set("%d" % index, 'FileSize', s)#在该section设置FileSize及其值
  index += 1

 cfg.write(open('cdays+1-result.txt',"w"))

def gtt(path):
 ''' get the three big size of files in the path
 @param path: specify the files of path
 @return one list contains item like (size, filename)
 '''
 all_file = {}
 for root, dirs, files in os.walk(path): #遍历path
  for onefile in files:
   fname = os.path.join(root, onefile)#获得当前处理文件的完整名字
   fsize = os.stat(fname).st_size#获得当前处理文件大小
   if all_file.has_key(fsize):#按照文件大小存储
    all_file[fsize].append(fname)
   else:
    all_file[fsize] = [fname]
 fsize_key = all_file.keys()#得到所有的文件大小
 fsize_key.sort()#排序,从小到大
 result = []
 for i in [-1, -2, -3]:#依次取最大的三个
  for j in all_file[fsize_key[i]]:#保存
   result.append((fsize_key[i], j))
 return result[:3]#返回前三个

if __name__ == "__main__":
 if len(sys.argv) == 1:
  print 'usage:\n\tpython cdays+1-exercise-2.py path'
 else:
  abs_path = os.path.abspath(sys.argv[1])
  if not os.path.isdir(abs_path):
   print '%s is not exist' % abs_path
  else:
   #from cdays+1-exercise-1 import get_top_three as gtt
   iniTT(gtt(abs_path))
}}}
=== CDays+2 ===
 * 如果在Karrigell 实例中,不复制 cdctools.py 到webapp 目录中,也可以令 index.ks 引用到?
    1. 修改python的环境变量PYTHONPATH,把cdctools.py的所在目录路径加入

    1. 在程序里动态的修改sys.path
,如下所示
{{{
#!python
import sys

# cdctools.py的路径添加到sys.path

sys.path.append('/home/shengyan/workspace/obp/CDays/cdays2/')

from cdctools import *

}}}

 * 经过本章Karrigell的初步学习,实现一个简易的web留言系统。主要利用Karrigell_quick_form实现提交留言并显示出来。
    1. 具体步骤:
1、下载karrigell,解压后,根据默认设置直接就可以运行了,但一般修改conf/下Karrigell.ini中的port=8081,表示使用端口8081,保存

2、将msg拷贝至webapps/,并在index.pih中增加链接<a href='msg/'> Message</a>

3、编辑msg中的index.ks,完成所需功能

4、cd至karrigell所在目录,输入python Karrigell.py运行后,在浏览器地址栏中输入localhost:8081就可以看到页面,点击Message链接即可到达。
{{{
#!python
# -*- coding: utf-8 -*-

import os,sys
import pickle # 神奇的序列化模块
from HTMLTags import * # Karrigell 提供页面输出支持模块
from Karrigell_QuickForm import Karrigell_QuickForm as KQF

def _htmhead(title):
    '''默认页面头声明
    @note: 为了复用,特别的组织成独立函式,根据Karrigell 非页面访问约定,函式名称前加"_"
    @param title: 页面标题信息
    @return: 标准的HTML代码
    '''
    htm = """<html><HEAD>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>%s</title></HEAD>
<body>"""%title
    return htm
## 默认页面尾声明
htmfoot="""
<h5>design by:<a href="mailto:[email protected]">lizzie</a>
    powered by : <a href="http://python.org">Python</a> +
 <a href="http://karrigell.sourceforge.net"> KARRIGELL 2.4.0</a>
</h5>
</body></html>"""

def index(**args):
    '''默认主
    @note: 使用简单的表单/链接操作来完成原有功能的界面化
    @param args: 数组化的不定参数
    @return: 标准的HTML页面
    '''
    print _htmhead("Leave Messages")
    p = KQF('fm_message','POST',"index","Message")
    p.addHtmNode('text','yname','Name',{'size':20,'maxlength':20})
    p.addTextArea('Words','10','90')
    p.addGroup(["submit","btn_submit","Submit","btn"])
    p.display()
    
    if 0 == len(QUERY):
        pass
    else:
        if "Submit" in QUERY['btn_submit']:
            yname = QUERY['yname']
            ywords = QUERY['Words']
            if 0 == len(ywords):
                print H3("please say something!")
            else:
                if 0 == len(yname):
                    yname = 'somebody'
                try:
                    msg = pickle.load(open("message.dump"))
                except:
                    msg = []
                msg.append((yname, ywords))
                index = len(msg)-1
                while index >= 0:
                    print H5(msg[index][0]+' says: ')
                    print P('------ '+msg[index][1])
                    index -= 1
                pickle.dump(msg,open("message.dump","w"))
        else:
            pass
    print htmfoot

}}}
=== CDays+3 ===
 * 熟悉线程相关知识后,利用Lock和RLock实现线程间的简单同步,使得10个线程对同一共享变量进行递增操作,使用加锁机制保证变量结果的正确。
{{{
#!python

}}}
 * 使用Queue实现多线程间的同步。比如说,十个输入线程从终端输入字符串,另十个输出线程依次获取字符串并输出到屏幕。
{{{
#!python

}}}
 * Python中的Event是用于线程间的相互通信,主要利用信号量机制。修改题一的程序,利用信号量重新实现多线程对同一共享变量进行递增操作。
{{{
#!python

}}}
== KDays ==
== 小结 ==
## 总体语法等等叙述,注意给出相关知识的阅读指导
##endInc

ObpLovelyPython/LpyAttach3answer (last edited 2009-12-25 07:14:24 by localhost)