进度条的打印
import sys,time
for i in range(20):
sys.stdout.write('$') #stdout是标准输出的意思,在一般电脑上,stdout的标准输出指的是计算机屏幕。
sys.stdout.flush()
time.sleep(0.1)
单线程下的并发运算:
import time
def consumer(name):
print("%s 准备吃包子啦!" %name)
while True:
baozi = yield
print("包子[%s]来了,被[%s]吃了!" %(baozi,name))
def producer(name):
c = consumer('A')
c2 = consumer('B')
c.__next__()
c2.__next__()
print("老子开始准备做包子啦!")
for i in range(10):
time.sleep(1)
print("做了2个包子!")
c.send(i)
c2.send(i)
producer("gavin")
生成数字+字母的验证码的小程序
__author__ = "Gavin"
import random
checkcode=''
for i in range(5):
current=random.randrange(0,5)
if current == i:
tmp=chr(random.randint(65,90))
else:
tmp=random.randint(0,9)
checkcode+=str(tmp)
print(checkcode)
异步I/O写的SocketServer
使用协程的方式,执行效率极高
server side
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
31
32
33
34
35
import sys
import socket
import time
import gevent
from geventimport socket,monkey
monkey.patch_all()
def server(port):
s= socket.socket()
s.bind(('0.0.0.0', port))
s.listen(500)
while True:
cli, addr= s.accept()
gevent.spawn(handle_request, cli)
def handle_request(conn):
try:
while True:
data= conn.recv(1024)
print("recv:", data)
conn.send(data)
if not data:
conn.shutdown(socket.SHUT_WR)
except Exception as ex:
print(ex)
finally:
conn.close()
if __name__== '__main__':
server(8001)
client side
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import socket
HOST= 'localhost' # The remote host
PORT= 8001 # The same port as used by the server
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
msg= bytes(input(">>:"),encoding="utf8")
s.sendall(msg)
data= s.recv(1024)
#print(data)
print('Received',repr(data))
s.close()
自己写的缓存系统