Python技巧汇总
来源:互联网 发布:安川机械手编程 编辑:程序博客网 时间:2024/06/05 08:16
#=============================================================================== #[数值/字符串/list/tuple] # 将整数转换为指定小数位的浮点数 n = 11 print "%.2f" % n # 11.00 # 数值类型转换 var1 = float(var2) var1 = int(var2) # 格式化字符串 print "%d,%c,%.2f,%s" % (a,b,c,d) # list和tuple相互转换 var = tuple(list_var) var = list(tuple_var) #=============================================================================== #[数据库] # 使用MySQLdb库 import MySQLdb # 创建数据库连接 conn = MySQLdb.connect(host="10.1.22.34",user="root",passwd="123",/ db="db_test",use_unicode=True,charset="utf8") cursor = conn.cursor() # 使用autocommit()就不需要commit() self.conn.autocommit(True) # 执行SQL命令 ret = cursor.execute("select * from db_table") #conn.commit() # 一定要提交,否则多用户操作时会出问题 if ret == 0: print "0条记录" return # 获取数据 data = cursor.fetchall() # 或者 cursor.fetchone() #conn.commit() # 如果不提交,有时候fetch***()会出问题 print data #=============================================================================== #[其他] # 延迟 import time time.sleep(0.5) # 运行命令行 os.system("gnome-session-save --kill --silent") # 注销当前用户 # 获取时间 from datetime import date date.today().strftime("%Y-%m-%d") # 年-月-日 # 随机数 import random list = random.sample(num_list, 50) # 由num_list得出50位随机数# 判断HTTP请求类型 if os.environ['REQUEST_METHOD'] == "POST": DoSomething()# 获取当前登录用户名 os.getlogin() import os,pwd pwd.getpwuid(os.getuid())[0]# 遍历目录下的文件 for f in sum([ [os.path.join(base,file) for file in files] for base,dirs,files in os.walk('/your/path/dir')],[]): print f