1.用户输入用户名和密码还有验证码.
用户可以有三次登录的机会. 但是验证码如果输入错误. 不计算在内.
from random import randint user = 'chenweixian' pwd = '123' count = 1 while count <= 3: Verify_code = '' for i in range(4): Verify_code += chr(randint(65, 90)) In_UserName = input('please input you username:') In_PassWord = input('please input you password:') In_Verify_Code = input('input verify_code__%s__:'%Verify_code).upper() if In_Verify_Code != Verify_code: print('Verify_Code is fail !!!') continue if In_UserName == user and In_PassWord == pwd: print('Login Successful !!! ') break else: print('Username or PassWord is fail,Please input again') count += 1 print('You Only have %s change to login' % (4 - count))
简版购物车
count1 = 1 while count1 <= 3: Name_Input = input('请输入用户名:') Pwd_Input = input('请输入密码:') if Name_Input == 'alex' and Pwd_Input == '123': Money_Input = int(input('请输入你的工资:')) while 1 : print('******商品菜单********') for i in enumerate(goods,1): print(i[0],i[1]['name'],i[1]['price']) num = input('请输入你想要购买的商品的编号:') if num.upper() == 'Q': print(dd) print('购物车') print('商品名称'' ','价格'' ','购买数量'' ','总价') for el in dd: print(el['name'],el['price'],el['count'],el['price']*el['count']) break num = int(num) if num < 1 or num > len(goods): print("您输入的商品不存在") continue if goods[num-1]['price'] < Money_Input: print(goods[num-1]) Money_Input -= goods[num-1]['price'] for i in dd: if i['name'] == goods[num-1]['name']: i['count'] = i['count']+1 break else: dd.append({'name':goods[num-1]['name'],'price':goods[num-1]['price'],'count':1}) else: while 1 : if goods[num - 1]['price'] > Money_Input: hh = input('余额不足,请充值:Y/N') if hh.lower() == 'y': Money_Input += int(input('请输入你要充值的金额:')) else: print('余额不足,重新选择商品') break else: Money_Input -= goods[num - 1]['price'] for i in dd: if i['name'] == goods[num - 1]['name']: i['count'] += 1 else: dd.append({'name': goods[num - 1]['name'], 'price': goods[num - 1]['price'], 'count': 1}) print(dd) break print('%s购买成功,你的余额为%s' %(goods[num-1]['name'],Money_Input)) else: if count1 == 3: print('你已经三次输入错误,退出系统') else: print('用户名或密码错误,请重新输入') count1 += 1
Hr
'''HR⼈⼒资源管理. 1. 菜单: ("查看员⼯信息","添加员⼯信息", "修改员⼯信息", "删除员⼯信息", "退出") 2. 添加员⼯信息: ⽤户输入员⼯的基本信息(id, name, birthday, salary, time), 将员⼯信息写入到⽂件 emp.db⽂件内 3. 修改员⼯信息: 显⽰所有员⼯信息. 然后让⽤户选择要修改的员⼯的id. 然后让⽤户输入员⼯的⼯ 资, 将员⼯的⼯资修改为⽤户输入的⼯资. 其余内容不做改动 4. 删除员⼯信息: 显⽰所有员⼯信息. 然后⽤户选择要删除的员⼯id, 根据⽤户输入的id删除该员⼯的 全部信息 5. 查看员⼯信息: 显⽰出所有员⼯的基本信息. 以上操作都需要围绕着emp.db来完成. 扩展(升级题): ⽤户的每⼀次操作成功都要将⽤户执⾏的操作记录在emp.log⽂件中(查看员⼯信息除 外). 例如: ⽤户选择"添加员⼯信息". 当添加动作执⾏完毕, 在emp.log中记录⼀句话: 管理员在 xxxx-xx-xx hh:mm:ss时间执⾏了添加员⼯信息操作. 添加的员⼯信息为: xxxxxxxxxxxxx 以此类推. 每次操作成功后都要记录信息. (查看员⼯信息除外) emp.db ⽂件中的内容格式⾃⼰定义. 这个没有要求. 但是要符合你⾃⼰的设计需求 ''' import time import os # 负责记录日志 def emplog(content): f = open("emp.log", mode="a", encoding="utf-8") f.write(content + " ") f.close() def chakan(): f = open("emp.db", mode="r", encoding="utf-8") print("工号 姓名 工资 生日") for line in f: d = eval(line.strip()) # print("%s %s %s %s" % (d['empno'], d['name'], d['salary'], d['birthday'])) print(f"{d['empno']} {d['name']} {d['salary']} {d['birthday']} ") print("员工信息显示完毕!") def tianjia(): while 1: # (id, name, birthday, salary, time) empno = input("请输入员工的empno: ") f = open("emp.db", mode="r", encoding="utf-8") for line in f: d = eval(line.strip()) if d['empno'] == empno: break else: name = input("请输入员工的姓名:") birthday = input("请输入员工的生日:") salary = input("请输入员工的工资:") intime = time.strftime("%Y-%m-%d") dic = {"empno":empno, "name":name,"birthday":birthday, "salary":salary, "intime":intime} f = open("emp.db", mode="a", encoding="utf-8") f.write(str(dic)+" ") f.close() print("添加成功") emplog("管理员在%s添加了一个员工, 该员工信息为%s" % (time.strftime("%Y-%m-%d %H:%M:%S"), str(dic))) return # 添加成功 f.close() def xiugai(): chakan() # 显示所有员工信息 empno = input("请输入你要修改的员工的工号:") f = open("emp.db", mode="r", encoding="utf-8") for line in f: d = eval(line.strip()) if d['empno'] == empno: break else: print("没有此员工") return f.close() salary = input("请输入该员工的工资") with open("emp.db", mode="r", encoding="utf-8") as f1, open("emp.db_副本", mode="w", encoding="utf-8") as f2: for line in f1: d = eval(line.strip()) if d['empno'] == empno: d['salary'] = salary emplog("管理员在%s修改了一个员工, 该员工信息为%s" % (time.strftime("%Y-%m-%d %H:%M:%S"), str(d))) f2.write(str(d) + " ") os.remove("emp.db") os.rename("emp.db_副本", "emp.db") def shanchu(): chakan() # 显示所有员工信息 empno = input("请输入你要删除的员工工号:") with open("emp.db", mode="r", encoding="utf-8") as f1, open("emp.db_副本", mode="w", encoding="utf-8") as f2: for line in f1: d = eval(line.strip()) if d['empno'] == empno: emplog("管理员在%s删除了一个员工, 该员工信息为%s" % (time.strftime("%Y-%m-%d %H:%M:%S"), str(d))) continue f2.write(str(d) + " ") os.remove("emp.db") os.rename("emp.db_副本", "emp.db") menu = ("查看员⼯信息","添加员⼯信息", "修改员⼯信息", "删除员⼯信息", "退出") while 1: for i in range(len(menu)): print(i+1, menu[i]) num = input("请输入你要执行的菜单") if num == '1': chakan() elif num == "2": tianjia() elif num == "3": xiugai() elif num == "4": shanchu() elif num == '5': print("系统退出") exit() else: print("对不起没有此菜单")
TCP类型scoket 通信(可以验证粘包现象,包含通信循环,连接循环部分)
import socket import subprocess server = socket.socket() ip_port = ('127.0.0.1',8080) server.bind(ip_port) server.listen(2) con,addr = server.accept() # print(addr) while 1 : client_cmd = con.recv(1024).decode('utf-8') # print('*****') sub = subprocess.Popen( client_cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE,) # print('********') cmd_res = sub.stdout.read() print(type(cmd_res)) con.sendall(cmd_res) print('结果长度>>>', len(cmd_res))
import socket client = socket.socket() ip_port = ('127.0.0.1',8080) client.connect(ip_port) while 1: client_cmd = client.send(input('请输入系统指令>>>').encode('utf-8')) cmd_result = client.recv(1024).decode('gbk') print(cmd_result)
进程池版的socket 并发聊天
#Pool内的进程数默认是cpu核数,假设为4(查看方法os.cpu_count()) #开启6个客户端,会发现2个客户端处于等待状态 #在每个进程内查看pid,会发现pid使用为4个,即多个客户端公用4个进程 from socket import * from multiprocessing import Pool import os server=socket(AF_INET,SOCK_STREAM) server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) server.bind(('127.0.0.1',8080)) server.listen(5) def talk(conn): print('进程pid: %s' %os.getpid()) while True: try: msg=conn.recv(1024) if not msg:break conn.send(msg.upper()) except Exception: break if __name__ == '__main__': p=Pool(5) while True: print('ggggg') conn,*_=server.accept() print('bbbbb') p.apply_async(talk,args=(conn,)) print('hhhhhh') # p.apply(talk,args=(conn,client_addr)) #同步的话,则同一时间只有一个客户端能访问
from socket import * client=socket(AF_INET,SOCK_STREAM) client.connect(('127.0.0.1',8080)) while True: msg=input('>>: ').strip() if not msg:continue client.send(msg.encode('utf-8')) msg=client.recv(1024) print(msg.decode('utf-8'))
多线程实现socket
import multiprocessing import threading import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind(('127.0.0.1',8080)) s.listen(5) def action(conn): while True: data=conn.recv(1024) print(data) msg = input('服务端输入:') #在多线程里面可以使用input输入内容,那么就可以实现客户端和服务端的聊天了,多进程不能输入 conn.send(bytes(msg,encoding='utf-8')) if __name__ == '__main__': while True: conn,addr=s.accept() p=threading.Thread(target=action,args=(conn,)) p.start() tcp_server.py
import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(('127.0.0.1',8080)) while True: msg=input('>>: ').strip() if not msg:continue s.send(msg.encode('utf-8')) data=s.recv(1024) print(data) tcp_client.py