使用:复制代码 代码如下:foldercleanup.py -d 10 -k c:\test\keepfile.txt c:\test表示对c:\test目录只保留最近10天的子文件夹和keepfile.txt中指定的子文件夹。代码:复制代码 代码如下:import osimport os.pathimport datetime  def getOption():  from optparse import OptionParser    des   = "clean up the folder with some options"  prog  = "foldercleanup"  ver   = "%prog 0.0.1"  usage = "%prog [options] foldername"    p = OptionParser(description=des, prog=prog, version=ver, usage=usage,add_help_option=True)  p.add_option('-d','--days',action='store',type='string',dest='days',help="keep the subfolders which are created in recent %days% days")  p.add_option('-k','--keepfile',action='store',type='string',dest='keepfile',help="keep the subfolders which are recorded in text file %keepfile% ")  options, arguments = p.parse_args()    if len(arguments) != 1:    print("error: must input one directory as only one parameter ")    return    return options.days, options.keepfile, arguments[0]  def preCheckDir(dir):  if(not os.path.exists(dir)):    print("error: the directory your input is not existed")    return  if(not os.path.isdir(dir)):    print ("error: the parameter your input is not a directory")    return      return os.path.abspath(dir)  def isKeepByDay(dir, day):  indays = False  if( day is not None) :    t = os.path.getctime(dir)    today = datetime.date.today()    createdate = datetime.date.fromtimestamp(t)    indate = today - datetime.timedelta(days = int(day))    print (createdate)    if(createdate >= indate):      indays = True  print (indays)  return indays  def isKeepByKeepfile(dir, keepfile):  needkeep = False  print (dir)  if (keepfile is not None):    try :      kf = open(keepfile,"r")      for f in kf.readlines():        print (f)        if (dir.upper().endswith("\\" + f.strip().upper())):          needkeep = True      kf.close()    except:      print ("error: keep file cannot be opened")  print(needkeep)  return needkeep    def removeSubFolders(dir, day, keepfile):  subdirs = os.listdir(dir)  for subdir in subdirs:    subdir = os.path.join(dir,subdir)    if ( not os.path.isdir(subdir)):      continue    print("----------------------")    if( (not isKeepByDay(subdir, day))and (not isKeepByKeepfile(subdir, keepfile))):      print("remove subfolder: " + subdir)      import shutil      shutil.rmtree(subdir,True)    def FolderCleanUp():  (day, keepfile, dir) = getOption()  dir = preCheckDir(dir)  if dir is None:    return  removeSubFolders(dir,day,keepfile)  if __name__=='__main__':  FolderCleanUp()对目录下保留最后的zip文件:复制代码 代码如下:def KeepLastNumZips(num)    def extractTime(f):        return os.path.getctime(f)    zipfiles = [os.path.join(zipdir, f)                for f in os.listdir(zipdir)                if os.path.splitext(f)[1] == ".zip"]    if len(zipfiles) > num:        zipfiles.sort(key=extractTime, reverse=True)        for i in range(num, len(zipfiles)):

seed() 设置生成随机数用的整数起始值。调用任何其他random模块函数之前调用这个函数。语法以下是seed()方法的语法:seed ( [x] )注意:此函数是无法直接访问的,所以需要导入seed模块,然后需要使用random静态对象来调用这个函数。参数     x -- 这是下一个随机数的种子。如果省略,则需要系统时间,以产生下一个随机数。返回值此方法不返回任何值。例子下面的例子显示了seed()方法的使用。#!/usr/bin/pythonimport randomrandom.seed( 10 )print "Random number with seed 10 : ", random.random()# It will generate same random numberrandom.seed( 10 )print "Random number with seed 10 : ", random.random()# It will generate same random numberrandom.seed( 10 )print "Random number with seed 10 : ", random.random()当我们运行上面的程序,它会产生以下结果:Random number with seed 10 : 0.57140259469Random number with seed 10 : 0.57140259469Random number with seed 10 :

python发送email还是比较简单的,可以通过登录邮件服务来发送,linux下也可以使用调用sendmail命令来发送,还可以使用本地或者是远程的smtp服务来发送邮件,不管是单个,群发,还是抄送都比较容易实现。先把几个最简单的发送邮件方式记录下,像html邮件,附件等也是支持的,需要时查文档即可1、登录邮件服务复制代码 代码如下:#!/usr/bin/env python  # -*- coding: utf-8 -*-  #python2.7x  #send_simple_email_by_account.py  @2014-07-30  #author: orangleliu    ''''' 使用python写邮件 simple 使用126 的邮箱服务 '''    import smtplib  from email.mime.text import MIMEText    SMTPserver = 'smtp.126.com'  sender = '[email protected]'  password = "xxxx"    message = 'I send a message by Python. 你好'  msg = MIMEText(message)    msg['Subject'] = 'Test Email by Python'  msg['From'] = sender  msg['To'] = destination    mailserver = smtplib.SMTP(SMTPserver, 25)  mailserver.login(sender, password)  mailserver.sendmail(sender, [sender], msg.as_string())  mailserver.quit()  print 'send email success'  2、调用sendmail命令 (linux)复制代码 代码如下:# -*- coding: utf-8 -*-  #python2.7x  #send_email_by_.py  #author: orangleliu  #date: 2014-08-15  ''''' 用的是sendmail命令的方式  这个时候邮件还不定可以发出来,hostname配置可能需要更改 '''    from email.mime.text import MIMEText  from subprocess import Popen, PIPE    def get_sh_res():      p = Popen(['/Application/2.0/nirvana/logs/log.sh'], stdout=PIPE)      return str(p.communicate()[0])    def mail_send(sender, recevier):      print "get email info..."      msg = MIMEText(get_sh_res())      msg["From"] = sender      msg["To"] = recevier      msg["Subject"] = "Yestoday interface log results"      p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)      res = p.communicate(msg.as_string())      print 'mail sended ...'    if __name__ == "__main__":      s = "[email protected]"      r = "[email protected]"      mail_send(s, r)  3、使用smtp服务来发送(本地或者是远程服务器)复制代码 代码如下:#!/usr/bin/env python  # -*- coding: utf-8 -*-  #python2.7x  #send_email_by_smtp.py  #author: orangleliu  #date: 2014-08-15  ''''' linux 下使用本地的smtp服务来发送邮件 前提要开启smtp服务,检查的方法 #ps -ef|grep sendmail #telnet localhost 25  这个时候邮件还不定可以发出来,hostname配置可能需要更改 '''  import smtplib  from email.mime.text import MIMEText  from subprocess import Popen, PIPE      def get_sh_res():      p = Popen(['/Application/2.0/nirvana/logs/log.sh'], stdout=PIPE)      return str(p.communicate()[0])    def mail_send(sender, recevier):      msg = MIMEText(get_sh_res())      msg["From"] = sender      msg["To"] = recevier      msg["Subject"] = "Yestoday interface log results"      s = smtplib.SMTP('localhost')      s.sendmail(sender, [recevier], msg.as_string())      s.quit()      print 'send mail finished...'    if __name__ == "__main__":      s = "[email protected]"      r =  s      mail_send(s,

复制代码 代码如下:import sysfrom PyQt4 import QtGui, QtCoreclass Window( QtGui.QMainWindow):    def __init__(self):        QtGui.QMainWindow.__init__(self)        self.setWindowTitle('hello')        self.resize(800,500)        menubar = self.menuBar()        self.file = menubar.addMenu('&file')        open = self.file.addAction('open')        self.connect(open,QtCore.SIGNAL('triggered()'),self.OnOpen)        save =self.file.addAction('save')        self.connect(save,QtCore.SIGNAL('triggered()'),self.OnSave)        self.file.addSeparator()        close = self.file.addAction('close')        self.connect(close,QtCore.SIGNAL('triggered()'),self.OnClose)        self.label = QtGui.QLabel('this is a google text')        self.label.setAlignment(QtCore.Qt.AlignCenter)        self.setCentralWidget(self.label)    def OnOpen(self):        self.label.setText('open')    def OnClose(self):        self.close()    def OnSave( self):        self.label.setText('save')    def contextMenuEvent(self,event):

Python3,开一个线程,间隔1秒把一个递增的数字写入队列,再开一个线程,从队列中取出数字并打印到终端#! /usr/bin/env python3import timeimport threadingimport queue# 一个线程,间隔一定的时间,把一个递增的数字写入队列# 生产者class Producer(threading.Thread): def __init__(self, work_queue): super().__init__() # 必须调用 self.work_queue = work_queue def run(self): num = 1 while True: self.work_queue.put(num) num = num+1 time.sleep(1) # 暂停1秒# 一个线程,从队列取出数字,并显示到终端class Printer(threading.Thread): def __init__(self, work_queue): super().__init__() # 必须调用 self.work_queue = work_queue def run(self): while True: num = self.work_queue.get() # 当队列为空时,会阻塞,直到有数据 print(num)def main(): work_queue = queue.Queue() producer = Producer(work_queue) producer.daemon = True # 当主线程退出时子线程也退出 producer.start() printer = Printer(work_queue) printer.daemon = True # 当主线程退出时子线程也退出 printer.start() work_queue.join() # 主线程会停在这里,直到所有数字被get(),并且task_done(),因为没有调用task_done(),所在这里会一直阻塞,直到用户按^Cif __name__ == '__main__': main()queue是线程安全的,从多个线程访问时无需加锁。如果在work_queue.get()之后调用work_queue.task_done(),那么在队列空时work_queue.join()会返回。这里work_queue.put()是间隔一定时间才往队列放东西,如果调用work_queue.task_done(),在数字1被get()后,队列空时,join()就返回,程序就结束了。也就是程序只打印了1然后就退出了。所以在这种使用情景下,不能调用task_done(),程序会一直循环下去。

分类:365bet娱乐城官网

时间:2016-05-13 01:34:25