def create_socket(self): try: self.socket = socket.socket() self.socket.connect(self.addr) P('连接服务器成功...') except Exception as e: P('create socket exception %s' % e)
def action_B(self): with lock: P('%s got lock in action_B %s' % (self.name, time.ctime())) time.sleep(2) with lock: P('%s got lock again in action_B %s' % (self.name, time.ctime())) time.sleep(1)
def read_fun(socket, mask): data = socket.recv(1000).decode('utf8') if data: print('received:%s' % data) socket.send(data.upper().encode('utf8')) else: P('no data received....')
def command_fanout(self): while True: cmd = input('>>>').strip() if cmd == 'exit': break cmd, file = cmd.split() if hasattr(self, cmd): # 使用反射. cmd_func = getattr(self, cmd) cmd_func(cmd, file) else: P('Command %s not found.' % cmd)
def foo(q): P('foo id q:%s' % id(q)) q.put('foo') q.put('123')
def app(environ, start_response): P(environ) P(start_response) start_response('200 OK', [('Content-Type', 'text/html')]) return [b'<h1>Hello wsgi server</h1>']
""" from pprint import pprint as P def hanoi(n, p1, p2, p3): """汉诺塔游戏,移动的次数为2^1 -1 次。 :param n: :param p1: :param p2: :param p3: :return: """ step_list = [] if n == 1: step = (p1, p3) step_list.append(step) else: step_list.extend(hanoi(n - 1, p1, p3, p2)) # 将n-1个盘子从p1移动到p2 # print('%s--->%s' % (p1, p3)) # 将第n个盘子从p1,移动到P3 step = (p1, p3) step_list.append(step) step_list.extend(hanoi(n - 1, p2, p1, p3)) # 将n-1个盘子从p2移动到p3 return step_list if __name__ == '__main__': n = eval(input("请输入盘子个数:")) step_list = hanoi(n, 1, 2, 3) P(step_list) print(len(step_list))
print('__set__ called.') print('self:%s, instance:%s,value:%s' % (self, instance, value)) if not isinstance(value, self.field_type): raise TypeError('%s expected type:%s, but input type:%s' % (self.field_name, self.field_type, type(value))) else: instance.__dict__[self.field_name] = value class People: name = Typed('name', str) age = Typed('age', int) salary = Typed('salary', float) def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary p1 = People('egon', 18, 20000.) p1.name # P(p1.__dict__) # P(People.__dict__) P(p1.__dict__) p1.name = 'sam' P(p1.__dict__) # p2 = People(23.0, 25, 200002.0)
@license: Apache Licence @contact: [email protected] @site: @software: PyCharm @file: 类的装饰器.py @time: 2018/5/20 11:31 """ from pprint import pprint as P def deco(obj): print('------------------%s' % obj) obj.x = 1 obj.y = 1 obj.z = 1 return obj @deco # test = deco(test), 装饰器等价于高阶函数。 def test(): '''test fun''' print('test函数运行。') P(test.__dict__) # test() # @deco # Foo = deco(Foo) # class Foo: # pass # # f1 = Foo() # print(f1.__dict__) # P(Foo.__dict__)
@version: v1.0 @author: Richard @license: Apache Licence @contact: [email protected] @site: @software: PyCharm @file: 类的装饰器-修订版.py @time: 2018/5/20 12:18 """ from pprint import pprint as P def Typed(**kwargs): print('111:%s' % kwargs) def deco(obj): for k, v in kwargs.items(): setattr(obj, k, v) return obj return deco @Typed(name='egon', age=30) # ==>1、Typed(x=1,y=2,z=3)-->deco. 2、@deco(Foo) class Foo: pass P(Foo.__dict__)
# encoding: utf-8 """ @version: v1.0 @author: Richard @license: Apache Licence @contact: [email protected] @site: @software: PyCharm @file: server.py @time: 2018/6/3 14:28 """ from pprint import pprint as P import socket server = socket.socket() server.bind(('127.0.0.1', 8089)) server.listen(10) while True: client, addr = server.accept() buf = client.recv(1024) client.sendall(bytes('HTTP/1.1 201 OK\r\n\r\n', 'utf8')) data = open('test.html', 'rb').read() P(data) client.sendall(data)
""" @version: v1.0 @author: Richard @license: Apache Licence @contact: [email protected] @site: @software: PyCharm @file: 进程间通信demo01.py @time: 2018/5/29 8:19 """ from pprint import pprint as P import multiprocessing import time, os def foo(q): P('foo id q:%s' % id(q)) q.put('foo') q.put('123') if __name__ == '__main__': q = multiprocessing.Queue() p = multiprocessing.Process(target=foo,args=(q,)) p.start() P('main id q:%s' % id(q)) P('q.get:%s' % q.get()) P('q.get:%s' % q.get())
def accept_fun(socket, mask): client_skt, client_addr = socket.accept() client_port = client_addr[1] P('client coming:%s' % client_port) SELECTOR.register(client_skt, selectors.EVENT_READ, read_fun)
def mul_n(n): mul = 1 for i in range(1, n + 1): mul *= i P('%s!=%s' % (n, mul))
def sum_n(n): tot = 0 for i in range(1, n + 1): tot += i P('sum=%s' % (tot))
def remove_ele(l): while l: a = l[-1] P('removing...%s' % a) time.sleep(1) l.remove(a)
else: instance.__dict__[self.field_name] = value def deco(**kwargs): def wrapper(obj): for k, v in kwargs.items(): setattr(obj, k, Typed(k, v)) return obj return wrapper @deco(name=str, age=int, salary=float, gender=str) class People: def __init__(self, name, age, salary, gender): self.name = name self.age = age self.salary = salary self.gender = gender p1 = People('egon', 18, 20000., 'F') # P(p1.__dict__) P(People.__dict__) P(p1.__dict__) # p1.name = 'sam' # P(p1.__dict__) # p2 = People(23.0, 25, 200002.0)
print('__get__ called..[%s].....[%s]' % (instance, owner)) if instance is None: return self res = self.func(instance) setattr(instance, self.func.__name__, res) # 第一次计算,后续从实例属性中取。 return res class Room: def __init__(self, name, lenght, width): self.name = name self.length = lenght self.width = width # @property # ===> area = property(area) @LazyProperty # ===> area = LazyProperty(area) #这就是描述符。 def area(self): return self.width * self.length @LazyProperty def test(self): return 'test' r1 = Room('wc', 1, 1) # P(Room.__dict__) # print(r1.__dict__) P(r1.area) P(Room.area) # P(Room.test)
from pprint import pprint as P class Foo: pass class Bar: pass # f1 = Foo() # # print(type(f1)) # print(type(Foo)) # print(type(Bar)) def __init__(self, name, age): self.name = name self.age = age FFo = type('FFo', (object,), {'x':1, '__init__': __init__}) print(type(FFo)) P(FFo.__dict__) # f1 = type(FFo) # # print(f1.x) # ff1 = FFo('sam', 32) P(FFo.__dict__) print(ff1.name) print(ff1.age)
# encoding: utf-8 """ @version: v1.0 @author: Richard @license: Apache Licence @contact: [email protected] @site: @software: PyCharm @file: 多线程利器-队列demo01.py @time: 2018/5/27 16:10 """ from pprint import pprint as P import threading, time import queue # 线程队列 q = queue.Queue(5) #FIFO #= [1, 2, 3, 4, 5] q.put(12) q.put('sam') q.put('eva') q.put((1,2)) q.put({'eva': 1.5}, block=False) # 如果满了则不阻塞,抛出异常。 while q: data = q.get(block=False)# 如果空了则不阻塞,抛出异常。 print(data) P('-------')