Python Base
来源:互联网 发布:软件动态测试工具 编辑:程序博客网 时间:2024/06/06 09:49
Python Base
1.Time
Annoying Time Conversion
import time# unix time chuotime.time()# Time time.localtime()#########################a.unix time stamp#b.time object#c.string ##########################----------------------------#a=>btime.localtime(time.time())#----------------------------#----------------------------#b=>atime.mktime(time.localtime())#----------------------------#----------------------------#b=>cstring = time.strftime('%Y%m%D %H%M%S',time.localtime())#----------------------------#----------------------------#c=>btime.stfptime(string , '%Y%m%D %H%M%S')#----------------------------
2.random
import randomprint random.randint(0,5)random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0print random.uniform(10, 20) print random.uniform(20, 10) print random.randint(12, 20) #生成的随机数n: 12 <= n <= 20 print random.randint(20, 20) #结果永远是20 #从指定范围内,按指定基数递增的集合中 获取一个随机数random.randrange(10, 100, 2) print random.choice("学习Python") print random.choice(["JGood", "is", "a", "handsome", "boy"]) print random.choice(("Tuple", "List", "Dict"))p = ["Python", "is", "powerful", "simple", "and so on..."] random.shuffle(p) print p 从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] slice = random.sample(list, 5) #从list中随机获取5个元素,作为一个片断返回 print slice print list #原有序列并没有改变。
3.java style’s python(no need but just for fun)
class DBFactory(object): rds=RedisConnector.reuse() __dayList=[] __oneDayFile=[] @property def dayList(self): return self.__dayList @dayList.setter def dayList(self,dlist): self.__dayList=dlist @property def oneDayFile(self): return self.__oneDayFile @oneDayFile.setter def oneDayFile(self,dlist): self.__oneDayFile=dlist @abstractmethod def getTimes(self): pass @abstractmethod def getLastDays(self): pass @abstractmethod def check(self): pass @abstractmethod def kdb_save(self): passclass ModelSetting(DBFactory): BASEDIR=MEDIA_ROOT+'/data_project/ModelSettings' def __init__(self): self.getLastDays() def getLastDays(self): daylist=sorted(os.listdir(self.BASEDIR))[-2:] self.dayList=[os.path.join(self.BASEDIR,x)for x in daylist] tmp=['/'.join([self.BASEDIR,x,'%s_model_settings_%s.csv'%(x,y)]) for x in daylist for y in ['day','night']] self.oneDayFile=[x for x in tmp if os.path.exists(x)] def kdb_save(self): for x in self.oneDayFile: print 'to db ' print x write_model_setting(x) def getTimes(self): return map(os.path.getmtime,self.oneDayFile) def check(self): print "ModelSetting checking begin..." rds_tmp=map(float,json.loads(self.rds.get('rss:modelsetting:checktime'))) cur_time=self.getTimes() if not rds_tmp: self.kdb_save() if rds_tmp and cur_time!=rds_tmp: self.kdb_save() self.rds.set('rss:modelsetting:checktime',json.dumps(cur_time))class TradeLog(DBFactory): BASEDIR=MEDIA_ROOT+'/data_project/TunnelLogs' def __init__(self): self.getLastDays() def getLastDays(self): '''get last 2 days return the list with 4 elems:''' '''eg./mnt/Dataproject/TunnelLogs/20170322/Day''' ModelSettingBaseDir =self.BASEDIR self.dayList=sorted(os.listdir(ModelSettingBaseDir))[-2: ] daylist=map(lambda x: os.path.join(ModelSettingBaseDir, x,'Day'), self.dayList) nightlist=map(lambda x: os.path.join(ModelSettingBaseDir, x,'Ngt'), self.dayList) tmp=[] self.dayList=daylist+nightlist for folderpath in self.dayList: if os.path.exists(folderpath): tlist=[os.path.join(folderpath,x)for x in os.listdir(folderpath)] tmp.append(tlist) self.oneDayFile=tmp def kdb_save(self): for x in self.dayList: print 'to db' if os.path.exists(x): print x write_tunnel_log(x) def getTimes(self): timelist=[] for x in self.oneDayFile: timelist.append(map(os.path.getmtime,x)) return timelist def check(self): print "TradeLog checking begin..." rds_tmp=json.loads(self.rds.get('rss:tunnel_log:checktime')) cur_time=self.getTimes() if not rds_tmp: self.kdb_save() if rds_tmp and cur_time!=rds_tmp: self.kdb_save() self.rds.set('rss:tunnel_log:checktime',json.dumps(cur_time))def run(): ms=ModelSetting() ms.check() ml=TradeLog() ml.check()if __name__=="__main__": run()
4.logging :python loggine demo
Demo1:
#encoding=utf-8import logginglogging.debug('This is debug message')logging.info('This is info message')logging.warning('This is warning message')
Demo2:
#import logging##logging.basicConfig(level=logging.DEBUG,# format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',# datefmt='%a, %d %b %Y %H:%M:%S',# filename='myapp.log',# filemode='w')# #logging.debug('This is debug message')#logging.info('This is info message')#logging.warning('This is warning message')
Demo3:
#log.pyimport logginglogging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='myapp.log', filemode='w')##################################################################################################定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#console = logging.StreamHandler()console.setLevel(logging.INFO)formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')console.setFormatter(formatter)logging.getLogger('').addHandler(console)#################################################################################################logging.debug('This is debug message')logging.info('This is info message')logging.warning('This is warning message')#test.pyfrom log import logginglogging.debug('This is debug message')logging.info('This is info message')logging.warning('This is warning message')
4.simple Test Demo: English reading.(just for fun)
#urlget.pyfrom lxml import etree url="http://www.dioenglish.com/home.php?mod=space&uid=114322&do=blog&id=55535"xp = '//div[@id="blog_article"]'def get(url,xp): t = urllib.urlopen(url).read() sele = etree.HTML(t) #content = sele.xpath('//div[@id="blog_article"]/p/span/font/text()') if xp[-2:] =='()': info = sele.xpath(xp) else: content = sele.xpath(xp) info = content[0].xpath('string(.)').encode('utf-8') return info------------------------------------------------------#main.pyfrom urlget import getfrom textwrap import wrapimport urlgett = get(urlget.url,urlget.xp)t = get('http://www.dioenglish.com/home.php?mod=space&uid=27677&do=blog&id=55547',urlget.xp)tt=wrap(t,100)t=[]for i in range(len(tt)): t.append("\033[1;31;43m%d\033[0m %s"%(i,tt[i]))print t[0]def l1(): for x in t: yield xdef l2(): for x in reversed(t): yield xc1=l1()c2=l2()def get(i,c): try: ss=[] for x in range(i): ss.append(c.next()) except StopIteration: pass return ss##print get(4,c2)#print get(4,c2)#print get(4,c2)#while True: st = raw_input(">") print repr(st) if st in ['n','']: print '\n'.join(get(4,c1)) if st == 'l': print '\n'.join(reversed(get(4,c2))) if st =='g 0': c1=l1() print '\n'.join(get(4,c1))
5.pacakge:without test
#sys.path.append('../')#sys.path.append('../agentproxy/')#sys.path.append('../site/')from agentproxy.rewrite_kdb import write_tunnel_logfrom agentproxy.rewrite_kdb import write_model_setting
阅读全文
0 0
- Python Base
- Python - abc (Abstract Base Classes)
- leetcode 504. Base 7 python
- [leetcode: Python]504. Base 7
- Python checkio "Building Base"解决方案
- base
- Base
- BASE
- base-``
- base
- Base
- base
- base
- Base
- Python中的int(x,base)函数
- Python:ImportError: No module named indexes.base
- Python标准库:内置函数int(x, base=10)
- User Base协同过滤的推荐系统,python实现
- Qt笔记·第一篇Hello Qt!
- YCSB测试HBase的使用方法
- 【python】linux下安装python
- python 虚拟环境
- 接入-分布式任务调度平台XXL-JOB
- Python Base
- 51nod 1424 零树
- 层模式
- Oracle:触发器
- API(get/post)
- 关于Java中的继承,包括重写、构造器、访问权限、构造过程等知识总结
- webstorm项目运行到apache服务器
- POJ
- 微积分公式大全