中文Python行者首页 文章模板

-- Chaox (2005-10-20)

1. 关于我

个人信息

Chaox

邮件

chaox.maillist[at]gmail.com

工作电话

移动电话

UC 号码

MSN

chaox08[at]hotmail.com

1.1. 工作日志

<< <  2007 / 11 >  >>
Mon Tue Wed Thu Fri Sat Sun
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30    

日志内容提要

1.2. 能力自述

刚刚开始学Python,希望聆听和参与大家的讨论

1.2.1. 技术

1.2.1.1. 实例1

新写了一个基于C/S的聊天工具,用了Threading,Pmw,socket 等

Server :

   1 # -------------------------------------------------
   2 # set up a server that will receive a connection
   3 # from a client, send a string to the client
   4 # and close the connection
   5 # Created by Chao Xiong 2005.Oct.
   6 # Version 1.1
   7 # -------------------------------------------------
   8 
   9 import socket
  10 import threading
  11 
  12 HOST = ""
  13 PORT = 4000
  14 # HOST = raw_input("Pls input the IP address of host: ")
  15 # PORT = int(raw_input("Pls input the port of host: "))
  16 # clientcounter = 1
  17 clientnumber = 2
  18 clients = []
  19 buf = 1024
  20 
  21 class client(threading.Thread):
  22     def __init__(self, server, ID):
  23 
  24         threading.Thread.__init__(self)
  25         self.connection = connections[ID]
  26         # self.friendcon = connection[1-ID]
  27         self.server = server
  28         self.ID = ID
  29         # self.friendID = 1 - ID
  30 
  31     def run(self):
  32         friendMessage = ""
  33         self.connection.send("Welcome to the Server! Client %s" % self.ID)
  34         friendMessage = self.connection.recv(buf)
  35         while 1:
  36 
  37             if friendMessage != "":
  38                 for con in connections:
  39                     con.send("Client %s : " % self.ID + friendMessage)
  40                 # self.connection.send("Client %s : " % self.ID + friendMessage)
  41                 # self.friendcon.send("Client %s : " % self.ID + friendMessage)                
  42                 print "Client %s : " % self.ID + friendMessage
  43                 friendMessage = ""
  44             try:
  45                 friendMessage = self.connection.recv(buf)
  46             except:
  47                 print "Client %s is quit" % self.ID
  48                 break
  49 
  50 
  51 class ChatServer:
  52     def __init__(self):
  53         self.HOST = ""
  54         self.PORT = 4000
  55         self.address = (self.HOST, self.PORT)
  56 
  57         self.clientcounter = 0
  58 
  59         self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  60         self.server.bind(self.address)
  61         self.display("Waiting for connection...")
  62         self.execute()
  63 
  64     def execute(self):
  65         self.clients = []
  66         global connections
  67         connections = []
  68         destination = []
  69         Id = 0
  70 
  71         while 1:
  72             self.server.listen(clientnumber)
  73             con, dest = self.server.accept()
  74             connections.append(con)
  75             destination.append(dest)
  76             self.clientcounter += 1
  77             self.clients.append(client(self.server, Id))
  78             self.clients[Id].start()
  79             # self.clients[i].run()
  80             self.display("Client%s is connected" % Id)
  81             Id += 1
  82 
  83     def display(self, message):
  84         print message
  85 
  86 def main():
  87     ChatServer().execute()
  88 
  89 if __name__ == "__main__":
  90     main()

Client :

   1 # ---------------------------------
   2 # chatting tools Client GUI
   3 # Created by Chao Xiong 2005.Oct
   4 # version 1.0
   5 # ---------------------------------
   6 
   7 from Tkinter import *
   8 import Pmw
   9 import threading
  10 import socket
  11 
  12 buf = 1024
  13 
  14 class ChatClient(Frame, threading.Thread):
  15     """A simple GUI for client"""
  16 
  17     def __init__(self, name = "newcomer"):
  18         """initialize the frame"""
  19 
  20         self.name = name
  21         self.thecontents = ""
  22 
  23         threading.Thread.__init__(self)
  24         Frame.__init__(self)
  25         self.pack(expand = YES, fill = BOTH)
  26         # self.master.title("Chatting %s" % self.name)
  27         self.master.title("Chatting %s" % self.name)
  28         self.master.geometry("400x300")
  29 
  30         self.chatting = Entry(self)
  31         self.chatting.pack(fill = X, padx = 5, pady = 5)
  32         self.chatting.bind("<Return>", self.sendmessage)
  33 
  34         self.contents = Pmw.ScrolledText(self, text_state = DISABLED)
  35         self.contents.pack(expand = NO, fill = BOTH, padx = 5, pady = 5)
  36 
  37         self.start()
  38 
  39     def sendmessage(self, event):
  40 
  41         self.thecontents = event.widget.get()
  42         if self.thecontents != "":
  43             self.chatting.delete(0,len(self.thecontents))
  44             self.connection.send(self.thecontents)
  45 
  46 
  47 
  48     def displaymessage(self, message):
  49         self.contents.text_state = NORMAL
  50         self.contents.appendtext(message)
  51         self.contents.appendtext("\n")
  52         self.contents.text_state = DISABLED
  53 
  54     def run(self):
  55         HOST = "127.0.0.1"
  56         PORT = 4000
  57         address = (HOST, PORT)
  58 
  59         self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  60         try:
  61             self.connection.connect(address)
  62         except:
  63             self.displaymessage("Call failed")
  64 
  65         serverMessage = self.connection.recv(buf)
  66 
  67         while 1:
  68 
  69             if serverMessage != "":
  70                 self.displaymessage(serverMessage)
  71                 serverMessage = ""
  72 
  73             try:
  74                 serverMessage = self.connection.recv(buf)
  75             except:
  76                 self.displaymessage("The Server is shut down!")
  77                 break
  78 
  79 
  80         self.connection.close()
  81 
  82 
  83 
  84 def main():
  85     ChatClient().mainloop()
  86 
  87 if __name__ == "__main__":
  88     main()

长是长了点,有些是废话。。。。

有个问题请教各位高手,现在在Windows下执行以上两段程序时(直接双击),除了出现 Pmw的窗口界面外,还会出现一个DOS窗口,不知怎么去掉这个DOS窗口??谢谢!

* 把文件的后缀改为.pyw,然后双击就不会出现dos窗口了。 -- limodou

1.2.1.2. 实例2(24点算法)

试着写了一个24点的程序,遍历所有的解法,最多是24×64×5=7680种可能。有点丑陋而且重解很多,不过还是发上来让大家扔一下。。。python真的是很强大啊~~

   1 from __future__ import division
   2 from operator import add, sub, mul
   3 from time import *
   4 
   5 
   6 
   7 div = lambda x, y : x/y
   8 ops = [add, sub, mul, div]
   9 opsc = ['+','-','*','/']
  10 equation = []
  11 
  12 data = input('Pls input the four numbers:(separate them by comma)')
  13 
  14 xtime = time()
  15 
  16 #--------------------------------------------------------
  17 # list all the sort according to the four numbers, it is
  18 # copied from AllStartFromGame at http://python.cn
  19 #--------------------------------------------------------
  20 def permute(seq):
  21   l = len(seq)
  22   if l == 1:
  23     return [seq]
  24   else:
  25     res=[]
  26     for i in range(len(seq)):
  27       rest = seq[:i] + seq[i+1:]
  28       for x in permute(rest):
  29         res.append(seq[i:i+1] + x)
  30     return res
  31 
  32 listofall = permute(data)
  33 newlist = list(set(listofall))
  34 
  35 
  36 #--------------------------------------------------------
  37 # consider the five different structures of combinations
  38 #--------------------------------------------------------
  39 for a in newlist:
  40     for i in range(4):
  41         for j in range(4):
  42             for k in range(4):
  43                 express = []
  44                 value = (a[0],opsc[i],a[1],opsc[j],a[2],opsc[k],a[3])
  45                 express.append("((%d %s %d) %s %d) %s %d" % value)
  46                 express.append("(%d %s (%d %s %d)) %s %d" % value)
  47                 express.append("%d %s ((%d %s %d) %s %d)" % value)
  48                 express.append("%d %s (%d %s (%d %s %d))" % value)
  49                 express.append("(%d %s %d) %s (%d %s %d)" % value)
  50                 for s in express:
  51                     try:
  52                         x = eval(s)
  53                     except:
  54                         continue
  55                     if x < 24.00001 and x > 23.99999:
  56                         equation.append(s)
  57 
  58 ytime = time()
  59 cacltime = ytime - xtime
  60 
  61 equation = list(set(equation))
  62 for e in equation:
  63     print e
  64 
  65 print "there are %d" % len(equation), "items at all"
  66 print "all the time of calculation is %s s" % cacltime

1.2.1.3. 实例3(24点游戏)

把24点的程序变成了游戏,适合学龄儿童和老年人玩,开发智力,保持思考。 :)

不过还是有bug,如不能接受小键盘输入。。。

如果大家发现bug,请写在下面,或者和我联系,谢谢~~

如果不喜欢那些图片,直接删掉就可以~图片是从网上当的,如果侵犯了谁的权利,请告知,我立刻撤了~

24pGameV5_source.zip Upload new attachment "24pGameV5_exe.zip"

1.2.2. 知识

1.2.3. 等等

2. 反馈

欢迎大家浇水啊!