Python全棧開發-有趣的小程序

進度條的打印

  import sys,time

  for i in range(20):
    sys.stdout.write('$')      #stdout是標準輸出的意思,在通常電腦上,stdout的標準輸出指的是計算機屏幕。
    sys.stdout.flush()
    time.sleep(0.1)python

 

單線程下的併發運算:

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  gevent  import  socket,monkey
monkey.patch_all()
 
 
def  server(port):
     =  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   dom

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
=  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()

 

 

 

本身寫的緩存系統

相關文章
相關標籤/搜索