一、args参数说明及用法
#一个参数
def show(arg):
print(arg)
show('111')
#两个参数
def show(arg1,arg2):
print(arg1,arg2)
show('ckl','zld')
#三个参数
def show(arg1,arg2,arg3):
print(arg1,arg2,arg3)
show('ckl','zld','love')
#默认参数
def show(arg1,arg2=888):
print(arg1,arg2)
show('ckl',)
*带默认值的不能写在前面,必须写在后面
#指定参数
def show(a1,a2):
print(a1,a2)
show(a2=893,a1='good luck number is')
#动态参数
def show(*args):
print(args)
show('ckl','zld','love')
*输出结果为元祖类型,就是把参数当做元祖来传入
#动态参数,接受字典类型的输入
def show(**kwargs):
print(kwargs)
show(n1='ckl',n2='love',n3='zld')
#万能参数
def show(*args,**kwargs):
print(args,kwargs)
show('ckl','love',11,44,['chun',88],('kk','mm'),n1='ka',n2='ba')
#如果传递的是列表和字典的变量,则使用如下方法
def show(*args,**kwargs):
print(args,kwargs)
CmList = ['11','22','33','44']
KmDic = {'ckl':'good','zld':'well'}
show(*CmList,**KmDic)
s1 = "{0} is {1}"
CList = ['spring','warm']
result = s1.format(*CList)
print(result)
s2 = "{name} love{who}"
Cdic = {'name':'ckl','who':'zld'}
res2 = s2.format(**Cdic)
print(res2)
func = lambda a: a + 1
ret = func(19)
print(ret)
#enumerate的使用方法
CkList = ['ckl','zld','love']
for i,item in enumerate(CkList,1):
print(i,item)
#1 ckl
#2 zld
#3 love
#map使用方法
Zlist = [11,22,33]
Clist = map(lambda x:x+100,Zlist)
print(list(Clist))
#[111,122,133]
#filter使用方法
def func(x):
if x > 33:
return True
else:
return False
li = [11,22,33,44,55]
result = filter(func,li)
list(result)
for i in result:
print(i)
#44
#55
#zip 对称生成新的列表
x = [1,2,3]
z = [4,5,6]
zipped = zip(x,z)
print(list(zipped))
#[(1, 4), (2, 5), (3, 6)]
二、位置参数与实参
def registrer(name,age,gender=22): print(name) print(age) print(gender) def wapper(*args,**args): #(*(1,5,7),**{'x':2,'y':19}) register(*args,**args) wrapper(1,5,7,x=2,y=19) #这样调用回报错1赋值给name,5赋值给age,7赋值给gender,剩下x=2,y=19多余参数,报错 wrapper('god',0) #这样正确
补充:命名参数
#命名关键字参数,在*后面定义的形参。必须是被以关键字实参传值 def usinfo(name,age,*,gender): print(name) print(age) print(gender) usinfo('ckl',19,'male') #这样会报错,因为*后面的参数必须是关键字参数。 #命名参数的作用:限制了*后面参数的形式
三、关于collections
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#Counter继承自dict所以拥有了dict的所有方法
import collections
obj = collections.Counter('todayisagooday')
print(obj)
ret = obj.most_common(3)
print(ret)
for k,v in obj.items():
print(k,v)
#Counter 的其他方法
CklObj = collections.Counter(['11','22','33'])
print(CklObj)
CklObj.update(['11','11','kaka'])
print(CklObj)
CklObj.subtract(['kaka'])
print(CklObj)
#根据添加的顺序,实现有序的字典
dic = collections.OrderedDict()
dic['k1'] = 'v1'
dic['k2'] = 'v2'
dic['k4'] = 'v4'
dic['k3'] = 'v3'
print(dic)
#可命名元祖
MytupleClass = collections.namedtuple('MytupleClass',['x','y','z'])
obj = MytupleClass(11,22,33)
print(obj.x)
print(obj.y)
print(obj.z)
#双向队列
d = collections.deque()
d.append('8')
d.append('9')
#左边扩展'3'
d.appendleft('3')
print(d)
print(d.count('8'))
#右边扩展
d.extend(['cc','kk','ll'])
print(d)
#左边扩展
d.extendleft(['zz','ll','dd'])
print(d)
#将最后一个放到第一个
d.rotate(1)
print(d)
#单项队列
import queue
q = queue.Queue()
q.put('ckl')
q.put('zld')
print(q.qsize())
print(q.get())
print(q.get())
三、关于deepcopy
#!/usr/bin/env python #-*- coding:utf-8 -*- import copy #对于数字、字符串而言,没有深浅拷贝 n1 = 123 print(id(n1)) n2 = n1 print(id(n2)) n3 = copy.deepcopy(n1) print(id(n3)) Dict1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]} #浅拷贝 Dict2 = copy.copy(Dict1) print(id(Dict1)) print(id(Dict2)) #打印的值不一样,因为浅copy没有copy列表里面的内存空间 print(id(Dict1['k3'])) print(id(Dict2['k3'])) #打印一样,因为只拷贝了k3字典的键 print("="*10) #深拷贝 Dict3 = copy.deepcopy(Dict1) print(id(Dict1)) print(id(Dict3)) print("") print(id(Dict1['k3'])) print(id(Dict3['k3'])) #完全不一样,完全深入拷贝了所以内存空间
四、关于file注意
#正确打开文件说明 with open('a.txt','r') as f_read: print(f_read.read()) #一次性打印所有内容,这个值是个str类型 with open('a.txt','r') as f_read: content=f_read.readlines() #一次性将内容全部加载成一个列表 for i in content: print(i) with open('a.txt','r') as f_read: for i in f_read: #正确打开文件,不需要一次性全加载至内存 print(i)
关于seek说明练习
#!/usr/bin/env python #-*- coding:utf-8 -*- """ fb = open('03.log','r') #fb.write('chuntianhuahuikai') ret = fb.read(5) #指定读取的字符数 tes = fb.tell() #查看当前指针位置 print(ret) print(tes) fb.seek(3) #指定移动指针的位置 cvb = fb.read(4) print(cvb) fb.close() """ fb = open('03.log','r+') fb.seek(4) #指定指针的起始位置 fb.truncate() #从指定的位置开始,截取之前的字符串 fb.close()
五、关于set补充
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#python-reference-readthedocs.io/en/latest
add : set添加元素
s1 = {'ckl','zld','love','ckl'}
s2 = {'ckl','zld'}
s1.add('kaka')
print(s1)
clear: 清空集合
s1 = {'ckl','zld','love','ckl'}
s1.clear()
print(s1)
copy:集合复制
s1 = {'ckl','zld','love','ckl'}
s2 = s1.copy()
print(s2)
difference:集合A的某元素在集合B没有出现,前后顺序有要求
s1 = {'ckl','zld','love','ckl'}
s2 = {'wukaka','ckl','love'}
s3 = s1.difference(s2)
s4 = s2.difference(s1)
print(s3) #{'zld'}
print(s4) #{'wukaka'}
difference_update:s1更新列表中的元素,如果s1元来的元素在更新列表中没有出现,则保留
s1 = {'ckl','zld','love','ckl'}
s1.difference_update(['ckl','kaka'])
print(s1)
discard:如果一个元素属于该集合则删除,否则不做任何操作
s1 = {'ckl','zld','love','ckl'}
s1.discard('ckl')
print(s1)
s2 = {'wukaka','ckl','love'}
s2.discard('kkk')
print(s2)
intersection:交集
s1 = {'ckl','zld','love','ckl'}
s2 = {'wukaka','ckl','love'}
s3 = s1.intersection(s2)
print(s3)
RBL
s1 = {'ckl','zld','love','ckl'}
s2 = {'wukaka','ckl','love'}
s3 = s1.intersection_update(s2)
print(s3)
isdisjoint:如果两个集合没有交集返回True,否则返回False
s1 = {'ckl','zld','love','ckl'}
s2 = {'wukaka','ckl','love'}
s3 = {'kkk','xxx'}
print(s1.isdisjoint(s2))
print(s1.isdisjoint(s3))
issubset:如果s2是s1的子集,则返回True,否则返回False
s1 = {'ckl','zld','love','ckl'}
s2 = {'wukaka','ckl','love'}
s3 = {'ckl','zld'}
print(s2.issubset(s1))
print(s3.issubset(s1))
pop:随机删除一个元素并返回
s1 = {'ckl','zld','love','ckl'}
s3 = s1.pop()
print(s3)
s4 = s1.pop()
print(s4)
remove:指定删除的元素
s1 = {'ckl','zld','love','ckl'}
s1.remove('ckl')
print(s1)
symmetric_difference:s1中的元素在s2中没有和s2中的元素在s1中没有
s1 = {'ckl','zld','love','ckl'}
s2 = {'wukaka','ckl','love'}
s3 = s1.symmetric_difference(s2)
print(s3)
union:并集
s1 = {'ckl','zld','love','ckl'}
s2 = {'wukaka','ckl','love'}
s3 = s1.union(s2)
print(s3)
update:s1没有的值,则添加
s1 = {'ckl','zld','love','ckl'}
s1.update(['kkk'])
print(s1)
六、修改haproxy脚本练习
6.1.修改haproxy配置文件
today is a good day !
have a good day!
backend www.ckl.com
server web10 172.16.110.11:9090 weight 1 maxconn 300
backend mysql
server db1 172.16.110.12:3306 weight 2 maxconn 200
6.2.修改haproxy脚本
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import json
import sys
import re
#定义需要输入的文件字典
BackContent = {"backend":"","record":{"server":"","ipaddr":"","weight":"","maxconn":""}}
#定义需要定位的域的地址,如www.ckl.com
def BackSerfunc():
while True:
BackSer = input("Please input your banckend group: ")
if BackSer != "":
BackContent["backend"] = BackSer
return BackSer
else:
print("You must enter a BackSer")
continue
#定义server名称
def SerNamefunc():
while True:
SerName = input("Please input youe server name: ")
if SerName != "":
BackContent["record"]["server"] = SerName
return SerName
else:
print("You must enter a SerName")
continue
#定义ip地址
def IPaddfunc():
while True:
IPaddress = input("please input your IP: ")
if IPaddress != "":
BackContent["record"]["ipaddr"] = IPaddress
return IPaddress
else:
print("Your must enter a IP")
continue
#定义后端weight
def BackContentfunc():
while True:
Weight = input("Please input your Weight: ")
if Weight != "":
BackContent["record"]["weight"] = Weight
return Weight
else:
print("Your must enter weight number: ")
continue
#定义最大连接数
def MaxConnfunc():
while True:
MaxConn = input("Please the Server Maxconn: ")
if MaxConn != "":
BackContent["record"]["maxconn"] = MaxConn
return MaxConn
else:
print("You must enter maxconn number: ")
continue
#修改haproxy的主程序
def ModifyFile():
#运行输入程序的函数
BackSerfunc()
ReSerName = SerNamefunc()
ReIpAddr = IPaddfunc()
ReWeight = BackContentfunc()
ReMaxConn = MaxConnfunc()
#打开文件,将内容写入到变量里
Hafile = open('haproxy.cfg','r')
#Hafile = open('tt.txt','r')
Fread = Hafile.read()
Hafile.close()
#将内容分隔成列表
a = Fread.split('\n')
#定义初始的行号
LineNum = 0
#定义需要插入的行号
CklNum = 0
#定义列表的长度
AllNum = len(a)
for i in a:
LineNum += 1
#如果指定的内容找到,就将行号记录到CklNum里
if BackContent["backend"] in i:
CklNum = LineNum
#定义其实的索引位置为0
AindexNum = 0
#循环从CklNum开始到结束的列表内容
for y in range(CklNum,AllNum):
#正则匹配,如果内容是\t或者空格开头,后面跟着是server,就为真
x = re.match(r"^server",a[y].strip("\t "))
if x:
#如内容未真,则索引位置就是y+1,因为索引从0开始
AindexNum = y + 1
break
#定义需要插入的内容
AddContent = "\t" + "server" + " "+ ReSerName + " " + ReIpAddr + " " \
+ "weight"+ " "+ ReWeight + " " + "maxconn" + " " + ReMaxConn
#插入内容到指定的列表位置,也就是索引位置
a.insert(AindexNum,AddContent)
#HaNewFile = open("tt.txt","w")
HaNewFile = open("haproxy.cfg","w")
#循环列表,将列表的内容写入文件里,会覆盖
for i in a:
HaNewFile.write(i+'\n')
HaNewFile.close()
#定义用户名密码
UserDict = {
"ckl":"123",
"zld":"456"
}
def LoginFunc():
while True:
userName = input("Please input your username: ")
for i in range(3):
'''判断用户是否存在'''
if userName in UserDict.keys():
passWord = input("please input your password: ")
if passWord == UserDict[userName]:
print("welcome to user login system!")
return "SUCCESS"
break
else:
'''计算剩余机会'''
leaveTimes = 2 - i
if leaveTimes > 0:
print("sorry , you have %s chance!" % leaveTimes)
elif leaveTimes == 0:
print("hollyshit, you must be reject and be locked!")
'''如果三次机会用完,则在密码后加#,锁定用户'''
sys.exit(0)
else:
print("who are you? i dont't know you!")
break
if __name__ == "__main__":
LoginFunc()
ModifyFile()
6.3.结果
today is a good day !
have a good day!
backend www.ckl.com
server web10 172.16.110.11:9090 weight 1 maxconn 300
server web9 2.3.4.5 weight 2 maxconn 300
backend mysql
server db1 172.16.110.12:3306 weight 2 maxconn 200
七.模拟数据库查询脚本
import os def open_file(*args): with open('user.log','r') as f_read: if len(args) == 0: for line in f_read: print(line) else: #转元组为字符串 all_args = str(args[0]) #将字符串转为列表 all_args = all_args.split(',') for line in f_read.readlines(): whole_line = line.strip('\n').split(',') #如果只有一个字段则打印相关字段结果 if len(all_args) == 1: print(whole_line[volume_dict[all_args[0]]]) else: #否则,生成一个空列表,将结果追加到列表里,再一并打印 r_list = [] for arg in all_args: if arg in volume_dict: r_list.append(whole_line[volume_dict[arg]]) print(r_list) def open_file_eight(*args,cs_x=0,cs_y=0,cs_z=0): # select * from userinfo where age > 10; new_cz_z = str(cs_z).strip(';') with open('user.log','r') as f_read: if len(args) == 0: for line in f_read.readlines(): whole_line = line.strip('\n').split(',') #判断条件输入的操作符 if cs_y == '>': if whole_line[volume_dict[cs_x]] > new_cz_z: print(line) elif cs_y == '<': if whole_line[volume_dict[cs_x]] < new_cz_z: print(line) elif cs_y == '=': if whole_line[volume_dict[cs_x]] == new_cz_z: print(line) elif cs_y == 'like': if new_cz_z in whole_line[volume_dict[cs_x]]: print(line) else: print("Error: operate symbol is not found") else: #转元组为字符串 all_args = str(args[0]) #将字符串转为列表 all_args = all_args.split(',') for line in f_read.readlines(): whole_line = line.strip('\n').split(',') #如果只有一个字段则打印相关字段结果 if len(all_args) == 1: if cs_y == '>': if whole_line[volume_dict[cs_x]] > new_cz_z: print(whole_line[volume_dict[all_args[0]]]) elif cs_y == '<': if whole_line[volume_dict[cs_x]] < new_cz_z: print(whole_line[volume_dict[all_args[0]]]) elif cs_y == '=': if whole_line[volume_dict[cs_x]] == new_cz_z: print(whole_line[volume_dict[all_args[0]]]) elif cs_y == 'like': if new_cz_z in whole_line[volume_dict[cs_x]]: print(whole_line[volume_dict[all_args[0]]]) else: print("Error: operate1 symbol is not found") else: #否则,生成一个空列表,将结果追加到列表里,再一并打印 r_list = [] for arg in all_args: if arg in volume_dict: #如果结果符合条件,则追加列表里 if cs_y == '>': if whole_line[volume_dict[cs_x]] > new_cz_z: r_list.append(whole_line[volume_dict[arg]]) elif cs_y == '<': if whole_line[volume_dict[cs_x]] < new_cz_z: r_list.append(whole_line[volume_dict[arg]]) elif cs_y == '=': if whole_line[volume_dict[cs_x]] == new_cz_z: r_list.append(whole_line[volume_dict[arg]]) elif cs_y == 'like': if new_cz_z in whole_line[volume_dict[cs_x]]: r_list.append(whole_line[volume_dict[arg]]) else: print("Error: operate1 symbol is not found") #如果列表不为空,则打印列表 if r_list != []: print(r_list) def insert_func(*args): all_line = [] with open('user.log','r') as f_read: for line in f_read.readlines(): all_line.append(line) #获取最后一行,并且生成列表,获取第一个字段,也就是id last_id = all_line[-1].split(',')[0] #最后一个字段转为数字类型,再计算 last_id=int(last_id) #最后一个字段自增 cur_id = last_id + 1 cur_id=str(cur_id) #生成一个空列表,添加第一个id字段 new_list = [] new_list.append(cur_id) #args为一个元祖,元祖第一个字段为值内容,循环第一个字段追加到列表里 for i in args[0]: new_list.append(i) #循环所有行,检查列表的手机号字段是否与当前要插入的手机号重复 for x in all_line: x_list = x.split(',') for y in x_list: if new_list[3] == y: print("Error: %s is duplicate" %y) return 1 #循环列表,如果当前字段为最后一个字段,将最后一个字段的";"去掉,在加入新列表 all_new_list = [] for m in new_list: if m == new_list[-1]: m = str(m).strip(';') all_new_list.append(m) else: all_new_list.append(m) #将新列表转为str形式 new_line_content = ",".join(all_new_list).replace("'",'') #将新行追加到文件里 with open('user.log','a') as f_app: f_app.writelines("\n%s"%new_line_content) with open('user.log','r') as f_read: for i in f_read: print(i) def delete_func(*args): #生成一个空列表,添加第一个id字段 new_list = [] #args为一个元祖,元祖第一个字段为值内容,循环第一个字段追加到列表里 for i in args[0]: if i == ';': continue else: new_list.append(i) if len(new_list) != 7: print("Syntax Error: delete error") return 1 #判断字段、表名、条件字段是否存在响应的列表或字典里,from,into,where if new_list[1] == s_action and new_list[2] == table_name and new_list[3] == s_condition: #判断字段及操作字符是否在响应列表或字段里 if new_list[4] in volume_dict and new_list[5] in s_operate: # print(new_list[4],new_list[5],new_list[6]) #打开原文件进行读,打开新文件进行写 with open('user.log','r') as f_read,open('user.log.swp','w') as f_write: for i in f_read: line_list = i.split(',') #当前的循环行的相关字段与输入参数进行比较 if new_list[5] == '>': if line_list[volume_dict[new_list[4]]] > new_list[6]: continue else: f_write.write(i) if new_list[5] == '<': if line_list[volume_dict[new_list[4]]] < new_list[6]: continue else: f_write.write(i) if new_list[5] == '=': if line_list[volume_dict[new_list[4]]] == new_list[6]: continue else: f_write.write(i) if new_list[5] == 'like': if new_list[6] in line_list[volume_dict[new_list[4]]]: continue else: f_write.write(i) else: print("Syntax Error: delete volume is not found") return 1 else: print("Syntax Error: delete syntax error") return 1 os.remove('user.log') os.renames('user.log.swp','user.log') with open('user.log','r') as fs_read: for y in fs_read: print(y) def update_func(*args): #生成一个空列表,添加第一个id字段 new_list = [] #args为一个元祖,元祖第一个字段为值内容,循环第一个字段追加到列表里 for i in args[0]: new_list.append(i) if len(new_list) < 10: print("Syntax Error: the parameter of update is too short") return 1 if new_list[-1] == ';': new_list.pop() # 循环列表,如果当前字段为最后一个字段,将最后一个字段的";"去掉,在加入新列表 all_new_list = [] for m in new_list: if m == new_list[-1]: m = str(m).strip(';') all_new_list.append(m) else: all_new_list.append(m) if all_new_list[1] == table_name and all_new_list[2] == update_action: if all_new_list[3] in volume_dict and all_new_list[4] in s_operate and all_new_list[6] == s_condition \ and all_new_list[7] in volume_dict and all_new_list[8] in s_operate: with open('user.log','r') as f_read,open('user.log.swp','w') as f_write: for i in f_read: line_list = i.split(',') # 当前的循环行的相关字段与输入参数进行比较 if all_new_list[8] == '>': if line_list[volume_dict[all_new_list[7]]] > all_new_list[9]: line_list[volume_dict[all_new_list[3]]] = all_new_list[5] f_write.write(','.join(line_list)) else: f_write.write(i) if all_new_list[8] == '<': if line_list[volume_dict[all_new_list[7]]] < all_new_list[9]: line_list[volume_dict[all_new_list[3]]] = all_new_list[5] f_write.write(','.join(line_list)) else: f_write.write(i) if all_new_list[8] == '=': if line_list[volume_dict[all_new_list[7]]] == all_new_list[9]: line_list[volume_dict[all_new_list[3]]] = all_new_list[5] f_write.write(','.join(line_list)) else: f_write.write(i) if all_new_list[8] == 'like': if all_new_list[9] in line_list[volume_dict[all_new_list[7]]]: line_list[volume_dict[all_new_list[3]]] = all_new_list[5] f_write.write(','.join(line_list)) else: f_write.write(i) os.remove('user.log') os.renames('user.log.swp','user.log') with open('user.log','r') as fs_read: for y in fs_read: print(y) def insert(cmd_content): #insert into info values(4,'zhang san',28,13478781459,IT,2018-09-02); #初始列表,按照空格来进行切分,为了提取into和表名 init_args = str(cmd_content).replace('(',' ').replace(')',' ').split() #按照values来切分成一个列表,为了提取全部为值的部分 all_args = str(cmd_content).replace('(','').replace(')','').split('values') #切分全部为值部分为一个新列表 s_all_args = all_args[1].split(',') #如果语句第二字段为into和第三字段为表名,则执行函数 if init_args[1] == 'into' and init_args[2] == table_name: insert_func(s_all_args) def delete(cmd_content): #delete from info where name = 'li bai'; #delete from info where age > 19; #delete from info where enroll_time like '2017'; if '\'' in cmd_content: all_arg_list = [] cmd_content = cmd_content.split('\'') para_list = str(cmd_content[0]).split() for y in para_list: all_arg_list.append(y) for i in cmd_content: if cmd_content.index(i) == 0: continue else: all_arg_list.append(i) sql_sentence = all_arg_list else: sql_sentence = cmd_content.split() delete_func(sql_sentence) def update(cmd_content): #update info set name = 'li hei' where name = 'li bai'; if '\'' in cmd_content: all_arg_list = [] cmd_content = cmd_content.split('\'') para_list = str(cmd_content[0]).split() for y in para_list: all_arg_list.append(y) for i in cmd_content: if cmd_content.index(i) == 0: continue else: all_arg_list.append(i) #生成一个新的列表,将第六字段拆分,加入新列表,第六字段如:where name = new_all_list = [] for i in all_arg_list: if all_arg_list.index(i) == 6: y = str(i).split() for x in y: new_all_list.append(x) else: new_all_list.append(i) sql_sentence = new_all_list else: sql_sentence = cmd_content.split() update_func(sql_sentence) def select(cmd_content): #select * from userinfo; #select name from userinfo; #select name,age from userinfo; #select name,age from userinfo where dept = 'IT'; #select * from useinfo where enroll_date like '2013'; #如果条件语句中存在单引号 if '\'' in cmd_content: all_arg_list = [] cmd_content = cmd_content.split('\'') para_list = str(cmd_content[0]).split() for y in para_list: all_arg_list.append(y) for i in cmd_content: if cmd_content.index(i) == 0: continue else: all_arg_list.append(i) sql_sentence = all_arg_list else: sql_sentence = cmd_content.split() #如果参数为4个,则为没有条件的查询 if len(sql_sentence) == 4: #如果为最后一个参数,则去掉';' s_end=sql_sentence[-1] s_end=str(s_end).split(';')[0] #如果条件为'*',则打印全部内容 if sql_sentence[1] == '*': if sql_sentence[2] == s_action and s_end == table_name: open_file() else: print("Select Syntax Error") #如果查询的字段大于1则执行 if len(sql_sentence[1]) > 1: all_args=str(sql_sentence[1]).split(',') for s_arg in all_args: if s_arg not in volume_dict: print("Error: %s volume is not found" %s_arg) return 1 if sql_sentence[2] == s_action and s_end == table_name: open_file(sql_sentence[1]) else: print("Select Syntax Error") elif len(sql_sentence) >= 8: #如果表的字段不存在,则提示 if sql_sentence[3] != table_name: print("Error: table is not esxit") return 1 if sql_sentence[1] == '*': if sql_sentence[2] == s_action and sql_sentence[4] == s_condition: if sql_sentence[5] in volume_dict and sql_sentence[6] in s_operate: open_file_eight(cs_x=sql_sentence[5],cs_y=sql_sentence[6],cs_z=sql_sentence[7]) else: print("Syntax Error select eight: volume not found") else: print("Select Syntax Error eight") if len(sql_sentence[1]) > 1: all_args = str(sql_sentence[1]).split(',') for s_arg in all_args: if s_arg not in volume_dict: print("Error: %s volume is not found" % s_arg) return 1 open_file_eight(sql_sentence[1],cs_x=sql_sentence[5],cs_y=sql_sentence[6],cs_z=sql_sentence[7]) else: print("The select Syntax error. ") #定义操作方法为一个字典 cmd_dict = { 'insert':insert, 'delete':delete, 'update':update, 'select':select } #定义字段为一个字典 volume_dict = { 'staff_id':0, 'name':1, 'age':2, 'phone':3, 'dept':4, 'enroll_date':5 } s_action = 'from' s_condition = 'where' table_name = 'info' s_operate = ['>','<','=','like'] update_action = 'set' def main_func(): while True: cmd_content=input('MySQL-5.7 >>>: ') if len(cmd_content) == 0: continue elif cmd_content == 'q': break else: all_args=cmd_content.split() if ';' not in all_args[-1]: print("Syntax Error: the end symbol must be ';'") continue if len(cmd_content.split(' ')) < 4: print("Syntax Error: parameter is too short") continue if all_args[0] in cmd_dict: cmd_dict[all_args[0]](cmd_content) main_func()
运行结果:
select:
insert:
delete:
update: