ITPub博客

首页 > 应用开发 > IT综合 > 常用python日期、日志、获取内容循环的代码片段

常用python日期、日志、获取内容循环的代码片段

原创 IT综合 作者:天空的鹰 时间:2017-03-02 16:50:44 0 删除 编辑

近段时间对shell脚本和python进行了梳理,将一些脚本中常用的内容,考虑多种方法整理出来,形成有用的代码片段,这样就可以在需要的时候直接使用,也可以用于备忘和思考。
本次整理的代码片段有: python中日期、时间常用获取方法; 记录处理日志的logging模块使用;从目录,文件,命名结果中,获取循环条件进行循环。
我将这些有用的代码片段整理在一个Python脚本中了,并且测试可用。
脚本内容如下:


点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. #_*_coding:utf8_*_

  3. #常用日期和时间
  4. import datetime,time
  5. today = datetime.date.today()
  6. yesterday = datetime.date.today() - datetime.timedelta(days=1)
  7. tomorrow = datetime.date.today() + datetime.timedelta(days=1)

  8. Today_nyr = int(datetime.datetime.strftime(today, '%Y%m%d'))
  9. Yesterday_nyr = int(datetime.datetime.strftime(yesterday, '%Y%m%d'))
  10. Tomorrow_nyr = int(datetime.datetime.strftime(tomorrow ,'%Y%m%d'))

  11. time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
  12. print "now time is {time}".format(time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

  13. print "normal type , today is {today} , yesterday is {yesterday} , tomorrow is {tommorrow} .".format(today=today,yesterday=yesterday,tommorrow=tomorrow)
  14. print "nyr style , today is {today} , yesterday is {yesterday} , tommrrow is {tommorrow} .".format(today=Today_nyr,yesterday=Yesterday_nyr,tommorrow=Tomorrow_nyr)
  15. #logging.info("now time is {time}".format(time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))))
  16. #logging.info("normal type , today is {today} , yesterday is {yesterday} , tomorrow is {tommorrow} .".format(today=today,yesterday=yesterday,tommorrow=tomorrow))
  17. #logging.info("nyr style , today is {today} , yesterday is {yesterday} , tommrrow is {tommorrow} .".format(today=Today_nyr,yesterday=Yesterday_nyr,tommorrow=Tomorrow_nyr))

  18. ###程序日志模块logging使用
  19. import logging
  20. import os

  21. THISFILEPATH = os.path.dirname(os.path.realpath(__file__))
  22. logfile = '{path}/python_test_file.log'.format(path=THISFILEPATH)
  23. logging.basicConfig(level=logging.DEBUG,
  24.                     format='%(asctime)s - %(filename)s - [line:%(lineno)d] %(levelname)s: %(message)s',
  25.                     datefmt='%Y-%m-%d %H:%M:%S %p',
  26.                     filename=logfile,
  27.                     #level=10,
  28.                     filemode='a')



  29. logging.info("This is a info.\n")
  30. logging.warn("This is a warning.\n")
  31. logging.error("This is a error.\n")
  32. #logging.log("This is a log. \n\n")
  33. logging.debug("This is a debug. \n\n")
  34. logging.critical("This is a critical \n\n\n")


  35. logging.info("now time is {time}".format(time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))))
  36. logging.info("normal type , today is {today} , yesterday is {yesterday} , tomorrow is {tommorrow} .".format(today=today,yesterday=yesterday,tommorrow=tomorrow))
  37. logging.info("nyr style , today is {today} , yesterday is {yesterday} , tommrrow is {tommorrow} .".format(today=Today_nyr,yesterday=Yesterday_nyr,tommorrow=Tomorrow_nyr))


  38. ###从一个目录中,取出所有文件名进行循环
  39. from subprocess import call

  40. File_Dir = "/tmp"
  41. File_List = os.listdir(File_Dir)
  42. for f in File_List:
  43.     if( f[0] == '.' ):
  44.         continue
  45.     else:
  46.         logging.info("{filename}".format(filename=f))

  47. ###读取一个文件的多行,进行循环
  48. #文件读取方法一:
  49. file = open("/tmp/3.txt")
  50. while 1:
  51.     line = file.readline()
  52.     if not line:
  53.         break
  54.     logging.info("this line is :{line}".format(line=line))

  55. #文件读取方法二:
  56. import fileinput
  57. for line in fileinput.input("/tmp/3.txt"):
  58.     logging.info("this line is :{line} .".format(line=line))

  59. #文件读取方法三:
  60. file = open("/tmp/3.txt")
  61. for line in file:
  62.     logging.info("this line is :{line} .".format(line=line))


  63. ###获取一个shell命令执行结果,进行循环
  64. #获取命令方法一:
  65. import subprocess
  66. shell_cmd = "df -h | awk '{print $1}'"
  67. p = subprocess.Popen("{cmd}".format(cmd=shell_cmd), shell=True, stdout=subprocess.PIPE)
  68. out = p.stdout.readlines()
  69. for line in out:
  70.     print line.strip()
  71.     logging.info(" file system is :{line} .".format(line=line.strip()))


  72. #获取命令方法二:
  73. for line in subprocess.Popen("df -h | awk '{print $1}'",shell=True,stdout=subprocess.PIPE).stdout.readlines():
  74.     print line.strip()
  75.     logging.info(" file system is :{line} .".format(line=line.strip()))


       上面的脚本,可使用 python 3.py 直接执行。
       脚本执行结果如下:


点击(此处)折叠或打开

  1. 2017-03-02 16:48:43 PM - 3.py - [line:38] INFO: This is a info.

  2. 2017-03-02 16:48:43 PM - 3.py - [line:39] WARNING: This is a warning.

  3. 2017-03-02 16:48:43 PM - 3.py - [line:40] ERROR: This is a error.

  4. 2017-03-02 16:48:43 PM - 3.py - [line:42] DEBUG: This is a debug.


  5. 2017-03-02 16:48:43 PM - 3.py - [line:43] CRITICAL: This is a critical



  6. 2017-03-02 16:48:43 PM - 3.py - [line:46] INFO: now time is 2017-03-02 16:48:43
  7. 2017-03-02 16:48:43 PM - 3.py - [line:47] INFO: normal type , today is 2017-03-02 , yesterday is 2017-03-01 , tomorrow is 2017-03-03 .
  8. 2017-03-02 16:48:43 PM - 3.py - [line:48] INFO: nyr style , today is 20170302 , yesterday is 20170301 , tommrrow is 20170303 .
  9. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: 40001501_20170302.csv
  10. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: proc_cpu_result
  11. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: qaucli_022317-18_15_41.log
  12. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: sfcbHttpSocket
  13. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: 1.py
  14. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: sfcbLocalSocket
  15. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: 2.txt
  16. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: null
  17. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: 3.txt
  18. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: 3.py
  19. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: hsperfdata_root
  20. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: updatehbaconf.sh.log
  21. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: proc_cpu_detail.txt
  22. 2017-03-02 16:48:43 PM - 3.py - [line:60] INFO: python_test_file.log
  23. 2017-03-02 16:48:43 PM - 3.py - [line:69] INFO: this line is :1

  24. 2017-03-02 16:48:43 PM - 3.py - [line:69] INFO: this line is :2

  25. 2017-03-02 16:48:43 PM - 3.py - [line:69] INFO: this line is :3

  26. 2017-03-02 16:48:43 PM - 3.py - [line:69] INFO: this line is :4

  27. 2017-03-02 16:48:43 PM - 3.py - [line:69] INFO: this line is :5

  28. 2017-03-02 16:48:43 PM - 3.py - [line:69] INFO: this line is :6

  29. 2017-03-02 16:48:43 PM - 3.py - [line:69] INFO: this line is :7

  30. 2017-03-02 16:48:43 PM - 3.py - [line:69] INFO: this line is :8

  31. 2017-03-02 16:48:43 PM - 3.py - [line:69] INFO: this line is :9

  32. 2017-03-02 16:48:43 PM - 3.py - [line:74] INFO: this line is :1
  33.   .
  34. 2017-03-02 16:48:43 PM - 3.py - [line:74] INFO: this line is :2
  35.   .
  36. 2017-03-02 16:48:43 PM - 3.py - [line:74] INFO: this line is :3
  37.   .
  38. 2017-03-02 16:48:43 PM - 3.py - [line:74] INFO: this line is :4
  39.   .
  40. 2017-03-02 16:48:43 PM - 3.py - [line:74] INFO: this line is :5
  41.   .
  42. 2017-03-02 16:48:43 PM - 3.py - [line:74] INFO: this line is :6
  43.   .
  44. 2017-03-02 16:48:43 PM - 3.py - [line:74] INFO: this line is :7
  45.   .
  46. 2017-03-02 16:48:43 PM - 3.py - [line:74] INFO: this line is :8
  47.   .
  48. 2017-03-02 16:48:43 PM - 3.py - [line:74] INFO: this line is :9
  49.   .
  50. 2017-03-02 16:48:43 PM - 3.py - [line:79] INFO: this line is :1
  51.   .
  52. 2017-03-02 16:48:43 PM - 3.py - [line:79] INFO: this line is :2
  53.   .
  54. 2017-03-02 16:48:43 PM - 3.py - [line:79] INFO: this line is :3
  55.   .
  56. 2017-03-02 16:48:43 PM - 3.py - [line:79] INFO: this line is :4
  57.   .
  58. 2017-03-02 16:48:43 PM - 3.py - [line:79] INFO: this line is :5
  59.   .
  60. 2017-03-02 16:48:43 PM - 3.py - [line:79] INFO: this line is :6
  61.   .
  62. 2017-03-02 16:48:43 PM - 3.py - [line:79] INFO: this line is :7
  63.   .
  64. 2017-03-02 16:48:43 PM - 3.py - [line:79] INFO: this line is :8
  65.   .
  66. 2017-03-02 16:48:43 PM - 3.py - [line:79] INFO: this line is :9
  67.   .
  68. 2017-03-02 16:48:43 PM - 3.py - [line:90] INFO: file system is :Filesystem .
  69. 2017-03-02 16:48:43 PM - 3.py - [line:90] INFO: file system is :/dev/sda2 .
  70. 2017-03-02 16:48:43 PM - 3.py - [line:90] INFO: file system is :tmpfs .
  71. 2017-03-02 16:48:43 PM - 3.py - [line:90] INFO: file system is :/dev/sda1 .
  72. 2017-03-02 16:48:43 PM - 3.py - [line:90] INFO: file system is :/dev/sda5 .
  73. 2017-03-02 16:48:43 PM - 3.py - [line:96] INFO: file system is :Filesystem .
  74. 2017-03-02 16:48:43 PM - 3.py - [line:96] INFO: file system is :/dev/sda2 .
  75. 2017-03-02 16:48:43 PM - 3.py - [line:96] INFO: file system is :tmpfs .
  76. 2017-03-02 16:48:43 PM - 3.py - [line:96] INFO: file system is :/dev/sda1 .
  77. 2017-03-02 16:48:43 PM - 3.py - [line:96] INFO: file system is :/dev/sda5 .


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/24638123/viewspace-2134599/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
多年数据库运维和架构经验,对 MySQL、Oracle、PostgreSQL、Greenplum、MongoDB 等多种常见数据库有丰富的运维实践经验,擅长数据库架构设计、维护优化、数据流转、Shell 和 Python 开发;乐于技术交流,网名 yumushui 进行了大量的技术总结和思考分享。

注册时间:2015-05-21

  • 博文量
    20
  • 访问量
    52617