Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1374401
  • 博文数量: 264
  • 博客积分: 5810
  • 博客等级: 大校
  • 技术积分: 3528
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-13 17:15
文章分类

全部博文(264)

文章存档

2011年(264)

分类: Python/Ruby

2011-04-27 16:37:52

  1. class system():
  2.     def initLog(self):
  3.         global LOG_FILE
  4.         import logging
  5.         logger = logging.getLogger()
  6.         hdlr = logging.FileHandler(LOG_FILE)
  7.         formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
  8.         hdlr.setFormatter(formatter)
  9.         logger.addHandler(hdlr)
  10.         logger.setLevel(logging.NOTSET)
  11.         return logger

  12.     def download(self,url,localfile=None,block_size=1024):
  13.         logging = self.initLog()
  14.         if localfile == None:
  15.             localfile = os.path.join(os.getcwd(),os.path.basename(url))
  16.         elif os.path.isdir(localfile):
  17.             localfile = os.path.join(localfile,os.path.basename(url))
  18.         elif os.path.isfile(localfile):
  19.             os.remove(localfile)
  20.         try:
  21.             file_handle = open(localfile,'wb')
  22.         except:
  23.             errors = '%s is illegal!' % localfile
  24.             logging.error(errors)
  25.             return 0
  26.         try:
  27.             data = urllib2.urlopen(url)
  28.         except:
  29.             errors = 'download %s error!' % os.path.basename(localfile)
  30.             logging.error(errors)
  31.             return 0
  32.         logging.info("Downloading %s ..." % os.path.basename(localfile))
  33.         len_all = int(data.info().getheader('Content-Length'))
  34.         d = data.read(block_size)
  35.         file_handle.write(d)
  36.         if (len_all < block_size):
  37.             logging.info("Download 100.0%")
  38.         else:
  39.             len_done=block_size
  40.             logging.info("%6.2f%s"%(float(len_done) * 100 / len_all,'%'))
  41.         while (len(d) >= block_size ):
  42.             d = data.read(block_size)
  43.             file_handle.write(d)
  44.             len_done=len_done+len(d)
  45.             logging.info("\b\b\b\b\b\b\b%6.2f%s" % (float(len_done) * 100 / len_all,'%'))
  46.         logging.info("\n")
  47.         file_handle.close()
  48.         return localfile

  49.     def test2(self,tgz_name):
  50.         logging = self.initLog()
  51.         logging.info("starting ....\n")
  52.         if not self.download('http://%s/%s' % (HTTP_SERVER,tgz_name)):
  53.             return [0,"DOWN"]
  54.         else:
  55.             return [1,"OK"]
阅读(1014) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~