博客是我工作的好帮手,遇到困难就来博客找资料
分类: 系统运维
2017-03-14 17:37:39
#encoding=utf-8
# -*- coding:utf-8 -*-
import os
import calendar
import datetime
import MySQLdb
import os, sys, re,string
import time, tarfile,getopt
import socket
import struct
reload(sys)
sys.setdefaultencoding('utf-8')
optmap = {
'dbuser': 'tongji',
'dbpass': '4871DE5C',
'dbhost': '206.3.3.192',
'dbport': 3306,
'dbname': 'basic'
}
code='201613'
now = int(time.time())
msgid=code+str(now)+'0001'
print msgid
f = file('/home/haoren/liu/1550035_ACCOUNT_'+msgid+'_0001_V2.xml','w+')
f1 = file('/home/haoren/liu/1550035_RELATIONACCOUNTINFO_'+msgid+'_0001_V2.xml','w+')
def log(line):
line = line + "\r\n"
f.write(line)
return
def log1(line):
line = line + "\r\n"
f1.write(line)
return
def sql_select(reqsql):
try:
db_conn = MySQLdb.connect(user=optmap['dbuser'], passwd=optmap['dbpass'], host=optmap['dbhost'], port=optmap['dbport'], db=optmap['dbname'], charset='utf8')
db_cursor=db_conn.cursor()
db_conn.query("use %s"%optmap['dbname'])
count = db_cursor.execute(reqsql)
ret = db_cursor.fetchall()
db_cursor.close()
db_conn.close
return ret
except MySQLdb.Error,e:
print "Mysql ERROR %d:%s" %(e.args[0], e.args[1])
return ''
def getusercoin():
reqsql = "select * from singer_auth_sample;"
#print reqsql
ret = sql_select(reqsql)
#print ret
#log('')
log('')
for row in ret:
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log('
log(' ')
log(' ')
log(' ')
#log(' ')
if str(row[27]).isdigit():
log(' ')
else:
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log('')
#
#log('')
log1('')
for row in ret:
log1(' ')
log1(' ')
log1(' ')
log1(' ')
log1(' ')
log1(' ')
log1(' ')
log1(' ')
log1(' ')
log1(' ')
log1('')
log('')
log('')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log1('')
log1('')
log1(' ')
log1(' ')
log1(' ')
log1(' ')
log1(' ')
log1(' ')
log1(' ')
log1(' ')
getusercoin()
log('')
log1('')
f.close()
f1.close()
#encoding=utf-8
# -*- coding:gb2312 -*-
import os
import calendar
import datetime
import MySQLdb
import os, sys, re,string
import time, tarfile,getopt
import socket
import struct
optmap = {
'dbuser': 'tongji',
'dbpass': '4871DE5CAF809AA2',
'dbhost': '206.3.3.192',
'dbport': 3306,
'dbname': 'basic'
}
f = file('/home/haoren/liu/.xml','w+')
def log(line):
line = line + "\r\n"
f.write(line)
return
def sql_select(reqsql):
try:
db_conn = MySQLdb.connect(user=optmap['dbuser'], passwd=optmap['dbpass'], host=optmap['dbhost'], port=optmap['dbport'], db=optmap['dbname'])
db_cursor=db_conn.cursor()
db_conn.query("use %s"%optmap['dbname'])
count = db_cursor.execute(reqsql)
ret = db_cursor.fetchall()
db_cursor.close()
db_conn.close
return ret
except MySQLdb.Error,e:
print "Mysql ERROR %d:%s" %(e.args[0], e.args[1])
return ''
def getusercoin():
reqsql = "select * from sin_auth_sample ;"
#print reqsql
ret = sql_select(reqsql)
#print ret
log('')
for row in ret:
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
#log(' ')
if str(row[27]).isdigit():
log(' ')
else:
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log('')
#
log('')
for row in ret:
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log('')
log('')
log('')
getusercoin()
log('')
f.close()
1、第一个程序:
print("Hello World!")
2、变量:只能是 数字,字母,下划线的任意组合
定义变量:
name = "deyi liu"#name:变量名,deyi liu:变量值
print("My name is",name)#调用变量
3、打印多行:
msg = '''
name = "deyi liu"
age = "24"
PIE = "常量"
'''
print(msg)
4、用户输入:
name = input("name:")
wu加密(getpass)
import getpass #导入getpass模块,密码加密
passworld = getpass.getpass("passworld:")
5、字符串拼接:
'''
#字符串拼接:(%s:占位符,s代表string
%d:占位符,d代表date
%f:占位符,f代表float)
'''
name = input("name:")#raw_input:python2.x这样写,效果等同于Python3.x的input
age = int(input("age:"))#int:integer 整型
print(type(age) , type(str(age)))#打印一个变量的数据类型
job = input("job:")
salary = input("salary:")
info = '''
---------info of %s-----------
name = %s
age = %d
job = %s
salary =%s
''' % (name,name,age,job,salary)
info2 = '''
---------info of {_name}-----------
name = {_name}
age = {_age}
job = {_job}
salary = {_salary}
''' .format(_name=name,
_age=age,
_job=job,
_salary=salary)
info3 = '''
---------info of {0}-----------
name : {0}
age : {1}
job : {2}
salary : {3}
''' .format(name,age,job,salary)
print(info)
print(info2)
print(info3)
6、if else 判断:
import getpass
real_username = "liudeyi"
real_passworld = "Aa111111"
username = input("username:")
passworld = getpass.getpass("passworld:")#在pycharm不能执行,需在cmd交互器里执行
if real_username == username and real_passworld == passworld :
print("Wlecome user {name} login...".format(name=username))
else:
print("Out!")
7、while 循环:
count = 0
while True:
print("count:",count)
count = count+1 #count +=1
8、猜数游戏-while:
age_of_oldboy = 56
count = 0
while count<3:
age = int(input("guess age:"))
if age == age_of_oldboy:
print("yes,you got it")
break #退出本次循环
elif age > age_of_oldboy:
print("think smaller")
else:
print("think bigger")
count = count+1
else:
print("you have tried too many times..fuck off")
9、for 循环:
for i in range(10):#内建函数range() ,它产生等差级数序列
print("loop:",i)
for i in range(0,10,2):#打印从0 开始打印到10,跳一个打一个;guess for.py2代表步长,默认是1
print("loop:",i)
for i in range(0,10,):
if i<5:
print("loop:",i)
else:
continue#跳出本次循环,进入下一循环
print("hehe")
for i in range(10):
print("-----------",i)
for j in range(10):
print(j)
if j>5:
break
10、猜数-for:
age_of_oldboy = 56
count = 0
for i in range(3):
age = int(input("guess age:"))
if age == age_of_oldboy:
print("yes,you got it")
break #退出本次循环
elif age > age_of_oldboy:
print("think smaller")
else:
print("think bigger")
else:
print("Your account has been locked")
1、常用数据类型
name = "jack"#字符串 string
age = 24#整型int
height =1.75#浮点型float
print(type(name),type(age),type(height))
2、字符串与bytes类型转换
msg = "我爱北京天安门"
print(msg.encode(encoding="utf-8"))#字符串转bytes类型
print(msg.encode(encoding="utf-8").decode(encoding="utf-8"))#bytes类型转字符串
3、字典
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号
({})中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
键必须是唯一的,但值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
'''
info = {
'stu1101':'jack',
'stu1102':'rose',
'stu1103':'marry'
}
print(info)
print(info['stu1101'])
info['stu1101']='杰克'#字典修改
info['stu1104']='Lily'#字典修改,不存在则添加
print(info)
print(info.get('stu1105'))#获取,有就返回值,没有返回none
del info['stu1101']#删除
info.pop('stu1102')#删除
info.popitem()#随机删除
print(info)
print('stu1106' in info )#判断stu1106是否在info字典里,在就返回TRUE,不在返回FALSE
#多级字典嵌套及操作:
city = {
"湖南省":{
"长沙市":["岳麓区","常德"]
},
"重庆市":{
"涪陵":["榨菜","一般"]
},
"北京市":{
"天安门":["长城","金山"]
}
}
print(city)
city["北京市"]["天安门"][0]="故宫"#修改
print(city)
print(city.values())#打印值
print(city.keys())#打印key
city.setdefault("上海市",{"浦东":["杨思","东方体育中心"]})#新增,有就返回其原来的值,没有就创建一个新的
city.setdefault("重庆市",{"浦东":["杨思","东方体育中心"]})
print(city)
a = {
'stu1101':'jack',
'stu1102':'rose',
'stu1103':'marry'
}
b = {
'stu1101':'jack',
1:2,
3:4
}
print(a)
a.update(b)
print(a)#更新,有替换,没有就新增
print(a.items())#字典转列表
c=dict.fromkeys([6,7,8],'test')#初始化一个新的字典,
print(c)
#字典的循环:
d = {
'stu1101':'jack',
'stu1102':'rose',
'stu1103':'marry'
}
for i in d:
print(i,d[i])
for j,k in d.items():
print(j,k)
4、字符串操作
name = "my \tname is jack"
print(name.capitalize())#capitalize()方法返回字符串的一个副本,只有它的第一个字母大写。对于8位的字符串,这个方法与语言环境相关。
print(name.count('a'))#count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
print(name.center(50,'-'))#center() 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格
print(name.encode(encoding='utf-8'))#encode() 方法以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。
print(name.endswith("ck"))#endswith() 方法用于判断字符串是否以指定后缀结尾
print(name.expandtabs(tabsize=30))# expandtabs() 方法把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8
print(name.find('name'))#find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始)
和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
print(name[name.find('name'):9])
name = "my name is {name} and {year} old "
print(name.format(name='jack',year=24))#格式化字符串的函数str.format()
print(name.format_map({'name':'jack','year':23}))
print(name.index('name'))#查找name的位置
print('as123'.isalnum())#isalnum() 方法检测字符串是否由字母和数字组成,如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False
print('asdA'.isalpha())# isalpha() 方法检测字符串是否只由字母组成。
print('21'.isdecimal())#isdecimal() 方法检查字符串是否只包含十进制字符;这种方法只存在于unicode对象。注意:定义一个十进制字符串,只需要在字符串前添加 'u' 前缀即可。str = u"this2009"
print('2341'.isdigit())#isdigit() 方法检测字符串是否只由数字组成
print('a1A'.isidentifier())#判断是不是一个合法的标识符
print('asd'.islower())#islower() 方法检测字符串是否由小写字母组成。
print('123'.isnumeric())# isnumeric() 方法检测字符串是否只由数字组成
print(' '.isspace())#isspace() 方法检测字符串是否只由空格组成
print('My Name'.istitle())# istitle() 方法检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写
print(''.isprintable())#printable :包含所有可打印字符的字符串
print('DSF'.isupper())#isupper() 方法检测字符串中所有的字母是否都为大写。
str = "-";
seq = ("a", "b", "c"); # 字符串序列
print(str.join(seq))#join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
print('+'.join(['1','2','3']))
print(name.ljust(50,'1'))# ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。
print(name.rjust(50,'1'))
print('asASasdf'.lower())#lower() 方法转换字符串中所有大写字符为小写
print('asASasdf'.upper())#upper() 方法转换字符串中所有小写字符为大写
print('name is jack'.lstrip('name'))#lstrip() 方法用于截掉字符串左边的空格或指定字符。
print('name is jack\n'.rstrip())#不填默认去掉右边空格和换行符
print('\nname is jack\n'.strip())#左右都去掉
#print(''.maketrans())
'''
maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
注:两个字符串的长度必须相同,为一一对应的关系。
'''
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
str = "this is string example....wow!!!"
print(str.translate(trantab))
print('my is is is is '.replace('is','was',3))#replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
print('my is is is is'.rfind('is'))#rfind() 返回字符串最后一次出现的位置,如果没有匹配项则返回-1。
print('my is is is is'.split('i'))#split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串
print('ab c\n\nde fg\rkl\r\n'.splitlines())#splitlines() 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
print('sadfAASDASDjasAS'.swapcase())#swapcase() 方法用于对字符串的大小写字母进行转换
print('jAck is'.title())#title() 方法返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())。
print('this is string example....wow!!!'.zfill(50))# zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0。
5、元组
names = ('jack','rose')#与列表类似,不同之处在于元组的元素不能修改
6、列表操作
names = ['zhangsan','lisi','wangwu','xieliu','xieliu']
names.append('xiaolu')#追加,默认在最后
names.insert(1,'chenglong')#插入
names.insert(3,'wangli')#插入
names[2]='xiedi'#修改
print(names)
print(names[0],names[2])
print(names[1:3])#切片,起始位置1包括,结束位置3不包括
print(names[-1])#取列表最后一个值
print(names[-2:])#取最后两个值
print(names.index('wangwu'))#查找wangwu的位置
print(names[names.index('wangwu')])
print(names.count('xieliu'))#统计xieliu的数量
#names.clear()#清空列表
names.reverse()#反转列表
names.sort()#排序
names2 = [1,2,3,4]
names.extend(names2)#合并names2到names
names3 = names.copy()#复制names到names3,注:只复制第一层(浅copy)
#delete
names.remove('zhangsan')#删除
del names[1]#删除
names.pop()#删除,未写下标默认删除最后一个
7、列表复制(浅copy&深copy)
import copy
names = ['zhangsan','lisi',['liudeyi','jack'],'xieliu','xieliu']
names2 = names.copy()#复制names到names2,注:只复制第一层(浅copy)
print(names)
print(names2)
names[0] = '张三'
names[2][0] = 'LIUDEYI'
print(names)
print(names2)
print('--------------------')
names = ['zhangsan','lisi',['liudeyi','jack'],'xieliu','xieliu']
#names2 = copy.copy(names)#浅copy,等同于names2 = names.copy()
names2 = copy.deepcopy(names)#深copy
print(names)
print(names2)
names[0] = '张三'
names[2][0] = 'LIUDEYI'
print(names)
print(names2)
print('--------------------')
#浅copy
person = ['name',['saving',100]]
'''
p1 = copy.copy(person)
p2 = person[:]
p3 = list(person)
'''
p1 = person[:]
p2 = person[:]
print(p1)
print(p2)
p1[0] = 'jack'
p2[0] = 'rose'
print(p1)
print(p2)
p1[1][1] = 50
print(p1)
print(p2)
8、列表循环
names = ['zhangsan','lisi',['liudeyi','jack'],'xieliu','xieliu']
print(names[0:-1:2])#步长切片,等同于print(names[::2])
for i in names:
print(i)
9、标准库:os
import os#os,语义为,所以肯定就是操作系统相关的功能了,可以处理文件和目录这些我们日常手动需要做的操作,就比如说:显示当前目录下所有文件/删除某个文件/获取文件大小……
#cmd_res = os.system("dir")#执行命令,不保存结果
cmd_res = os.popen("dir").read()
print("-->",cmd_res)
os.mkdir("new dir")#创建目录
10、简单的购物车程序
product_list = [
('iPhone',5800),
('Mac Pro',9800),
('Bike',800),
('Watch',10600),
('coffee',31),
('Alex Python',120)
]
shopping_list=[]
salary = input("input your salary:")
if salary.isdigit():#isdigit() 方法检测字符串是否只由数字组成
salary=int(salary)
while True:
for index,item in enumerate(product_list):#enumerate 函数用于遍历序列中的元素以及它们的下标
print(index,item)
user_choice=input("选择要买的商品>>>:")
if user_choice.isdigit():
user_choice=int(user_choice)
if user_choice=0:
p_item=product_list[user_choice]
if p_item[1]<=salary:#买得起
shopping_list.append(p_item)
salary-=p_item[1]
print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m"%(p_item[0],salary))
else:
print("\033[41;1m你的余额只剩[%s]啦,余额不足\033[0m"%(salary))
else:
print("product code [%s] is not exist!"%(user_choice))
elif user_choice=='q':
print('---------shopping list--------')
for p in shopping_list:
print(p)
print("your current balance is:",salary)
exit()
else:
#print('error')
exit()
#encoding=utf-8
# -*- coding:gb2312 -*-
import os
import calendar
import datetime
import MySQLdb
import os, sys, re,string
import time, tarfile,getopt
import socket
import struct
optmap = {
'dbuser': 'tongji',
'dbpass': '4871DE5CAF809AA2',
'dbhost': '206.3.3.192',
'dbport': 3306,
'dbname': 'basic'
}
f = file('/home/haoren/liuniannian/mysql.xml','w+')
def log(line):
line = line + "\r\n"
f.write(line)
return
def sql_select(reqsql):
try:
db_conn = MySQLdb.connect(user=optmap['dbuser'], passwd=optmap['dbpass'], host=optmap['dbhost'], port=optmap['dbport'], db=optmap['dbname'])
db_cursor=db_conn.cursor()
db_conn.query("use %s"%optmap['dbname'])
count = db_cursor.execute(reqsql)
ret = db_cursor.fetchall()
db_cursor.close()
db_conn.close
return ret
except MySQLdb.Error,e:
print "Mysql ERROR %d:%s" %(e.args[0], e.args[1])
return ''
def getusercoin():
reqsql = "select * from sin_auth_sample ;"
#print reqsql
ret = sql_select(reqsql)
#print ret
log('')
for row in ret:
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
#log(' ')
if str(row[27]).isdigit():
log(' ')
else:
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log('')
#
log('')
for row in ret:
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log(' ')
log('')
log('')
log('')
getusercoin()
log('')
f.close()
1、第一个python程序:
print("Hello World!")
2、变量:只能是 数字,字母,下划线的任意组合
定义变量:
name = "deyi liu"#name:变量名,deyi liu:变量值
print("My name is",name)#调用变量
3、打印多行:
msg = '''
name = "deyi liu"
age = "24"
PIE = "常量"
'''
print(msg)
4、用户输入:
name = input("name:")
wu加密(getpass)
import getpass #导入getpass模块,密码加密
passworld = getpass.getpass("passworld:")
5、字符串拼接:
'''
#字符串拼接:(%s:占位符,s代表string
%d:占位符,d代表date
%f:占位符,f代表float)
'''
name = input("name:")#raw_input:python2.x这样写,效果等同于Python3.x的input
age = int(input("age:"))#int:integer 整型
print(type(age) , type(str(age)))#打印一个变量的数据类型
job = input("job:")
salary = input("salary:")
info = '''
---------info of %s-----------
name = %s
age = %d
job = %s
salary =%s
''' % (name,name,age,job,salary)
info2 = '''
---------info of {_name}-----------
name = {_name}
age = {_age}
job = {_job}
salary = {_salary}
''' .format(_name=name,
_age=age,
_job=job,
_salary=salary)
info3 = '''
---------info of {0}-----------
name : {0}
age : {1}
job : {2}
salary : {3}
''' .format(name,age,job,salary)
print(info)
print(info2)
print(info3)
6、if else 判断:
import getpass
real_username = "liudeyi"
real_passworld = "Aa111111"
username = input("username:")
passworld = getpass.getpass("passworld:")#在pycharm不能执行,需在cmd交互器里执行
if real_username == username and real_passworld == passworld :
print("Wlecome user {name} login...".format(name=username))
else:
print("Out!")
7、while 循环:
count = 0
while True:
print("count:",count)
count = count+1 #count +=1
8、猜数游戏-while:
age_of_oldboy = 56
count = 0
while count<3:
age = int(input("guess age:"))
if age == age_of_oldboy:
print("yes,you got it")
break #退出本次循环
elif age > age_of_oldboy:
print("think smaller")
else:
print("think bigger")
count = count+1
else:
print("you have tried too many times..fuck off")
9、for 循环:
for i in range(10):#内建函数range() ,它产生等差级数序列
print("loop:",i)
for i in range(0,10,2):#打印从0 开始打印到10,跳一个打一个;guess for.py2代表步长,默认是1
print("loop:",i)
for i in range(0,10,):
if i<5:
print("loop:",i)
else:
continue#跳出本次循环,进入下一循环
print("hehe")
for i in range(10):
print("-----------",i)
for j in range(10):
print(j)
if j>5:
break
10、猜数-for:
age_of_oldboy = 56
count = 0
for i in range(3):
age = int(input("guess age:"))
if age == age_of_oldboy:
print("yes,you got it")
break #退出本次循环
elif age > age_of_oldboy:
print("think smaller")
else:
print("think bigger")
else:
print("Your account has been locked")
1、常用数据类型
name = "jack"#字符串 string
age = 24#整型int
height =1.75#浮点型float
print(type(name),type(age),type(height))
2、字符串与bytes类型转换
msg = "我爱北京天安门"
print(msg.encode(encoding="utf-8"))#字符串转bytes类型
print(msg.encode(encoding="utf-8").decode(encoding="utf-8"))#bytes类型转字符串
3、字典
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号
({})中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
键必须是唯一的,但值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
'''
info = {
'stu1101':'jack',
'stu1102':'rose',
'stu1103':'marry'
}
print(info)
print(info['stu1101'])
info['stu1101']='杰克'#字典修改
info['stu1104']='Lily'#字典修改,不存在则添加
print(info)
print(info.get('stu1105'))#获取,有就返回值,没有返回none
del info['stu1101']#删除
info.pop('stu1102')#删除
info.popitem()#随机删除
print(info)
print('stu1106' in info )#判断stu1106是否在info字典里,在就返回TRUE,不在返回FALSE
#多级字典嵌套及操作:
city = {
"湖南省":{
"长沙市":["岳麓区","常德"]
},
"重庆市":{
"涪陵":["榨菜","一般"]
},
"北京市":{
"天安门":["长城","金山"]
}
}
print(city)
city["北京市"]["天安门"][0]="故宫"#修改
print(city)
print(city.values())#打印值
print(city.keys())#打印key
city.setdefault("上海市",{"浦东":["杨思","东方体育中心"]})#新增,有就返回其原来的值,没有就创建一个新的
city.setdefault("重庆市",{"浦东":["杨思","东方体育中心"]})
print(city)
a = {
'stu1101':'jack',
'stu1102':'rose',
'stu1103':'marry'
}
b = {
'stu1101':'jack',
1:2,
3:4
}
print(a)
a.update(b)
print(a)#更新,有替换,没有就新增
print(a.items())#字典转列表
c=dict.fromkeys([6,7,8],'test')#初始化一个新的字典,
print(c)
#字典的循环:
d = {
'stu1101':'jack',
'stu1102':'rose',
'stu1103':'marry'
}
for i in d:
print(i,d[i])
for j,k in d.items():
print(j,k)
4、字符串操作
name = "my \tname is jack"
print(name.capitalize())#capitalize()方法返回字符串的一个副本,只有它的第一个字母大写。对于8位的字符串,这个方法与语言环境相关。
print(name.count('a'))#count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
print(name.center(50,'-'))#center() 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串。默认填充字符为空格
print(name.encode(encoding='utf-8'))#encode() 方法以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。
print(name.endswith("ck"))#endswith() 方法用于判断字符串是否以指定后缀结尾
print(name.expandtabs(tabsize=30))# expandtabs() 方法把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8
print(name.find('name'))#find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始)
和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。
print(name[name.find('name'):9])
name = "my name is {name} and {year} old "
print(name.format(name='jack',year=24))#格式化字符串的函数str.format()
print(name.format_map({'name':'jack','year':23}))
print(name.index('name'))#查找name的位置
print('as123'.isalnum())#isalnum() 方法检测字符串是否由字母和数字组成,如果 string 至少有一个字符并且所有字符都是字母或数字则返回 True,否则返回 False
print('asdA'.isalpha())# isalpha() 方法检测字符串是否只由字母组成。
print('21'.isdecimal())#isdecimal() 方法检查字符串是否只包含十进制字符;这种方法只存在于unicode对象。注意:定义一个十进制字符串,只需要在字符串前添加 'u' 前缀即可。str = u"this2009"
print('2341'.isdigit())#isdigit() 方法检测字符串是否只由数字组成
print('a1A'.isidentifier())#判断是不是一个合法的标识符
print('asd'.islower())#islower() 方法检测字符串是否由小写字母组成。
print('123'.isnumeric())# isnumeric() 方法检测字符串是否只由数字组成
print(' '.isspace())#isspace() 方法检测字符串是否只由空格组成
print('My Name'.istitle())# istitle() 方法检测字符串中所有的单词拼写首字母是否为大写,且其他字母为小写
print(''.isprintable())#printable :包含所有可打印字符的字符串
print('DSF'.isupper())#isupper() 方法检测字符串中所有的字母是否都为大写。
str = "-";
seq = ("a", "b", "c"); # 字符串序列
print(str.join(seq))#join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
print('+'.join(['1','2','3']))
print(name.ljust(50,'1'))# ljust() 方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串。如果指定的长度小于原字符串的长度则返回原字符串。
print(name.rjust(50,'1'))
print('asASasdf'.lower())#lower() 方法转换字符串中所有大写字符为小写
print('asASasdf'.upper())#upper() 方法转换字符串中所有小写字符为大写
print('name is jack'.lstrip('name'))#lstrip() 方法用于截掉字符串左边的空格或指定字符。
print('name is jack\n'.rstrip())#不填默认去掉右边空格和换行符
print('\nname is jack\n'.strip())#左右都去掉
#print(''.maketrans())
'''
maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
注:两个字符串的长度必须相同,为一一对应的关系。
'''
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
str = "this is string example....wow!!!"
print(str.translate(trantab))
print('my is is is is '.replace('is','was',3))#replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
print('my is is is is'.rfind('is'))#rfind() 返回字符串最后一次出现的位置,如果没有匹配项则返回-1。
print('my is is is is'.split('i'))#split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串
print('ab c\n\nde fg\rkl\r\n'.splitlines())#splitlines() 按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
print('sadfAASDASDjasAS'.swapcase())#swapcase() 方法用于对字符串的大小写字母进行转换
print('jAck is'.title())#title() 方法返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())。
print('this is string example....wow!!!'.zfill(50))# zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0。
5、元组
names = ('jack','rose')#与列表类似,不同之处在于元组的元素不能修改
6、列表操作
names = ['zhangsan','lisi','wangwu','xieliu','xieliu']
names.append('xiaolu')#追加,默认在最后
names.insert(1,'chenglong')#插入
names.insert(3,'wangli')#插入
names[2]='xiedi'#修改
print(names)
print(names[0],names[2])
print(names[1:3])#切片,起始位置1包括,结束位置3不包括
print(names[-1])#取列表最后一个值
print(names[-2:])#取最后两个值
print(names.index('wangwu'))#查找wangwu的位置
print(names[names.index('wangwu')])
print(names.count('xieliu'))#统计xieliu的数量
#names.clear()#清空列表
names.reverse()#反转列表
names.sort()#排序
names2 = [1,2,3,4]
names.extend(names2)#合并names2到names
names3 = names.copy()#复制names到names3,注:只复制第一层(浅copy)
#delete
names.remove('zhangsan')#删除
del names[1]#删除
names.pop()#删除,未写下标默认删除最后一个
7、列表复制(浅copy&深copy)
import copy
names = ['zhangsan','lisi',['liudeyi','jack'],'xieliu','xieliu']
names2 = names.copy()#复制names到names2,注:只复制第一层(浅copy)
print(names)
print(names2)
names[0] = '张三'
names[2][0] = 'LIUDEYI'
print(names)
print(names2)
print('--------------------')
names = ['zhangsan','lisi',['liudeyi','jack'],'xieliu','xieliu']
#names2 = copy.copy(names)#浅copy,等同于names2 = names.copy()
names2 = copy.deepcopy(names)#深copy
print(names)
print(names2)
names[0] = '张三'
names[2][0] = 'LIUDEYI'
print(names)
print(names2)
print('--------------------')
#浅copy
person = ['name',['saving',100]]
'''
p1 = copy.copy(person)
p2 = person[:]
p3 = list(person)
'''
p1 = person[:]
p2 = person[:]
print(p1)
print(p2)
p1[0] = 'jack'
p2[0] = 'rose'
print(p1)
print(p2)
p1[1][1] = 50
print(p1)
print(p2)
8、列表循环
names = ['zhangsan','lisi',['liudeyi','jack'],'xieliu','xieliu']
print(names[0:-1:2])#步长切片,等同于print(names[::2])
for i in names:
print(i)
9、标准库:os
import os#os,语义为操作系统,所以肯定就是操作系统相关的功能了,可以处理文件和目录这些我们日常手动需要做的操作,就比如说:显示当前目录下所有文件/删除某个文件/获取文件大小……
#cmd_res = os.system("dir")#执行命令,不保存结果
cmd_res = os.popen("dir").read()
print("-->",cmd_res)
os.mkdir("new dir")#创建目录
10、简单的购物车程序
product_list = [
('iPhone',5800),
('Mac Pro',9800),
('Bike',800),
('Watch',10600),
('coffee',31),
('Alex Python',120)
]
shopping_list=[]
salary = input("input your salary:")
if salary.isdigit():#isdigit() 方法检测字符串是否只由数字组成
salary=int(salary)
while True:
for index,item in enumerate(product_list):#enumerate 函数用于遍历序列中的元素以及它们的下标
print(index,item)
user_choice=input("选择要买的商品>>>:")
if user_choice.isdigit():
user_choice=int(user_choice)
if user_choice=0:
p_item=product_list[user_choice]
if p_item[1]<=salary:#买得起
shopping_list.append(p_item)
salary-=p_item[1]
print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m"%(p_item[0],salary))
else:
print("\033[41;1m你的余额只剩[%s]啦,余额不足\033[0m"%(salary))
else:
print("product code [%s] is not exist!"%(user_choice))
elif user_choice=='q':
print('---------shopping list--------')
for p in shopping_list:
print(p)
print("your current balance is:",salary)
exit()
else:
#print('error')
exit()
#!/usr/bin/python
#encoding=utf-8
# -*- coding:utf-8 -*-
import os
import calendar
import datetime
import MySQLdb
import os, sys, re,string
import time, tarfile,getopt
import socket
import struct
reload(sys)
sys.setdefaultencoding('utf-8')
optmap = {
'dbuser': 'im_tongji',
'dbpass': 'AA264CE0CEE9A85F22C',
'dbhost': '2.7.5.121',
'dbport': 3306,
'dbname': 'webim_basic'
}
code='201613'
now = int(time.time())
msgid=code+str(now)
print msgid
#f = file('/home/haoren/liuniannian/picture/1550035_ACCOUNT_'+msgid+'_0001_V2.xml','w+')
f = file('/1550035_ACCOUNT/1550035_3_ACCOUNT_'+msgid+'_0001_V2.xml','w+')
#f1 = file('/home/haoren/liuniannian/picture/1550035_RELATIONACCOUNTINFO_'+msgid+'_0001_V2.xml','w+')
f1 = file('/1550035_ACCOUNT/1550035_3_RELATIONACCOUNTINFO_'+msgid+'_0001_V2.xml','w+')
def log(line):
line = line + "\r\n"
f.write(line)
return
def log1(line):
line = line + "\r\n"
f1.write(line)
return
def sql_select(reqsql):
try:
db_conn = MySQLdb.connect(user=optmap['dbuser'], passwd=optmap['dbpass'], host=optmap['dbhost'], port=optmap['dbport'], db=optmap['dbname'], charset='utf8')
db_cursor=db_conn.cursor()
db_conn.query("use %s"%optmap['dbname'])
count = db_cursor.execute(reqsql)
ret = db_cursor.fetchall()
db_cursor.close()
db_conn.close
return ret
except MySQLdb.Error,e:
print "Mysql ERROR %d:%s" %(e.args[0], e.args[1])
return ''
def getusercoin():
reqsql = "select * from singer_auth where status = 10 and ip !='NULL' and not imid in (61508337,84525809,);"
#print reqsql
ret = sql_select(reqsql)
#print ret
#log('
log('
for row in ret:
log(' ')
log('
log('
log('
if str(row[9]).strip() == '0' and str(row[10]).strip() == '0':
log('
elif str(row[9]).strip() == '0' and str(row[10]).strip() != '0':
log('
elif str(row[9]).strip() != '0' and str(row[10]).strip() == '0':
log('
else:
log('
log('
log('
log('
log('
log('
#log('
#if str(row[27]).isdigit():
# log('
#else:
log('
log('
log('
log('
if str(row[12]).strip() == '0':
log('
else:
log('
log(' ')
log('
#
#log('
log1('
for row in ret:
log1(' ')
log1('
log1('
log1('
log1('
log1('
log1('
log1('
log1(' ')
log1('
log('')
log('
log('
log(' ')
log('
log('
log('
log('
log(' ')
log('
log1('')
log1('
log1('
log1(' ')
log1('
log1('
log1('
log1('
log1(' ')
log1('
getusercoin()
log('
log1('
f.close()
f1.close()
#!/bin/bash
userlist=`mysql -ummnnu_tongji -p4871DE5CAF809AA264CE0CEE9A85F22C -h 2.3.3.1 -e "use webmmnnu_basic;select mmnnuid from singer_auth where status=10 and ip != 'NULL';"|awk 'NR>1'`
rm -fr /home/haoren/liu/picture/mmnnuididcardpic.tar.gz
echo "$userlist" >/home/haoren/liu/picture/123456.txt
sed -i '/61508337/d' /home/haoren/liu/picture/123456.txt
sed -i '/84525809/d' /home/haoren/liu/picture/123456.txt
sed -i '/85639044/d' /home/haoren/liu/picture/123456.txt
sed -i '/68559276/d' /home/haoren/liu/picture/123456.txt
sed -i '/86150650/d' /home/haoren/liu/picture/123456.txt
sed -i '/87552763/d' /home/haoren/liu/picture/123456.txt
sed -i '/49072058/d' /home/haoren/liu/picture/123456.txt
sed -i '/85189327/d' /home/haoren/liu/picture/123456.txt
sed -i '/87684553/d' /home/haoren/liu/picture/123456.txt
sed -i '/60548575/d' /home/haoren/liu/picture/123456.txt
sed -i '/56924418/d' /home/haoren/liu/picture/123456.txt
sed -i '/23154709/d' /home/haoren/liu/picture/123456.txt
sed -i '/60614639/d' /home/haoren/liu/picture/123456.txt
sed -i '/89873552/d' /home/haoren/liu/picture/123456.txt
sed -i '/80941906/d' /home/haoren/liu/picture/123456.txt
sed -i '/60831598/d' /home/haoren/liu/picture/123456.txt
sed -i '/83801587/d' /home/haoren/liu/picture/123456.txt
sed -i '/56606257/d' /home/haoren/liu/picture/123456.txt
sed -i '/61263496/d' /home/haoren/liu/picture/123456.txt
sed -i '/85050826/d' /home/haoren/liu/picture/123456.txt
sed -i '/85640098/d' /home/haoren/liu/picture/123456.txt
sed -i '/57841055/d' /home/haoren/liu/picture/123456.txt
sed -i '/60614639/d' /home/haoren/liu/picture/123456.txt
sed -i '/80941906/d' /home/haoren/liu/picture/123456.txt
sed -i '/28992438/d' /home/haoren/liu/picture/123456.txt
sed -i '/85217588/d' /home/haoren/liu/picture/123456.txt
sed -i '/89001403/d' /home/haoren/liu/picture/123456.txt
sed -i '/85210515/d' /home/haoren/liu/picture/123456.txt
sed -i '/83003756/d' /home/haoren/liu/picture/123456.txt
cd /1550035_ACCOUNT/
for i in `cat /home/haoren/liu/picture/123456.txt`
do
idcardpic1=`mysql -ummnnu_tongji -p4871DE5CAF809AA264CE0CEE9A85F22C -h 2.3.3.1 -e "use webmmnnu_basic;select idcardpic1 from singer_auth where mmnnuid=$i ;"|awk 'NR>1'`
idcardpic2=`mysql -ummnnu_tongji -p4871DE5CAF809AA264CE0CEE9A85F22C -h 2.3.3.1 -e "use webmmnnu_basic;select idcardpic2 from singer_auth where mmnnuid=$i ;"|awk 'NR>1'`
identifypic=`mysql -ummnnu_tongji -p4871DE5CAF809AA264CE0CEE9A85F22C -h 2.3.3.1 -e "use webmmnnu_basic;select identifypic from singer_auth where mmnnuid=$i ;"|awk 'NR>1'`
#echo $idcardpic1
#echo $idcardpic2
#echo "$i"",""$idcardpic1"",""$idcardpic2"",""$identifypic" >>mingdanduiyingbiao.txt
curl -O $idcardpic1
curl -O $idcardpic2
curl -O $identifypic
done
cd /1550035_ACCOUNT/
tar czvf 1550035_3_ACCOUNT_2016131490063738_0001_V2.tar.gz *.jpeg *.jpg 1550035_*.xml
split -b 100m 1550035_3_ACCOUNT_2016131490063738_0001_V2.tar.gz 1550035_3_ACCOUNT_2016131490063738_0001_V2.tar.gz
time1=`date -d"1 days ago" +%y%m%d`
mv /1550035_ACCOUNT/1550035_3_ACCOUNT_2016131490063738_0001_V2.tar.gza* /log/${time1}/
for m in `ls /log/${time1}/ |grep tar.gz`
do
/home/haoren/liu/picture/md5.pl.exe /log/${time1}/$m >>/log/${time1}/IMmmnnuPortIp.FILELIST.${time1}
done
/usr/local/bin/ncftpput -R -m -u monitor -p Ryk 2.3.3.2 /MM/day/log/${time1}/IM-SJ01-ServerWebIpPort/ /log/${time1}/1550035_3_ACCOUNT_2016131490063738_0001_V2.tar.gza*
/usr/local/bin/ncftpput -R -m -u monitor -p Ryk 2.3.3.2 /MM/day/log/${time1}/IM-SJ01-ServerWebIpPort/ /log/${time1}/IMmmnnuPortIp.FILELIST.${time1}
#rm -fr /1550035_ACCOUNT/*.jpeg
#rm -fr /1550035_ACCOUNT/*.jpg
#rm -fr /1550035_ACCOUNT/*.xml
#rm -fr /1550035_ACCOUNT/*.tar.gz*