Python全栈开发-有趣的小程序

Python全栈开发-有趣的小程序

进度条的打印

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

import sys
import socket
import time
import gevent

from gevent import 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   

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

原文发布于微信公众号 - 志学Python(gh_755651538c61)

原文发表时间:2019-09-06

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券