近段时间对shell脚本和Python进行了梳理,将一些脚本中常用的内容,考虑多种方法整理出来,形成有用的代码片段,这样就可以在需要的时候直接使用,也可以用于备忘和思考。
本次整理的代码片段有: python中日期、时间常用获取方法; 记录处理日志的logging模块使用;从目录,文件,命名结果中,获取循环条件进行循环。
我将这些有用的代码片段整理在一个Python脚本中了,并且测试可用。
脚本内容如下:
#!/usr/bin/env python
#_*_coding:utf8_*_
#常用日期和时间
import datetime,time
today = datetime.date.today()
yesterday = datetime.date.today() - datetime.timedelta(days=1)
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
Today_nyr = int(datetime.datetime.strftime(today, '%Y%m%d'))
Yesterday_nyr = int(datetime.datetime.strftime(yesterday, '%Y%m%d'))
Tomorrow_nyr = int(datetime.datetime.strftime(tomorrow ,'%Y%m%d'))
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
print "now time is {time}".format(time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
print "normal type , today is {today} , yesterday is {yesterday} , tomorrow is {tommorrow} .".format(today=today,yesterday=yesterday,tommorrow=tomorrow)
print "nyr style , today is {today} , yesterday is {yesterday} , tommrrow is {tommorrow} .".format(today=Today_nyr,yesterday=Yesterday_nyr,tommorrow=Tomorrow_nyr)
#logging.info("now time is {time}".format(time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))))
#logging.info("normal type , today is {today} , yesterday is {yesterday} , tomorrow is {tommorrow} .".format(today=today,yesterday=yesterday,tommorrow=tomorrow))
#logging.info("nyr style , today is {today} , yesterday is {yesterday} , tommrrow is {tommorrow} .".format(today=Today_nyr,yesterday=Yesterday_nyr,tommorrow=Tomorrow_nyr))
###程序日志模块logging使用
import logging
import os
THISFILEPATH = os.path.dirname(os.path.realpath(__file__))
logfile = '{path}/python_test_file.log'.format(path=THISFILEPATH)
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(filename)s - [line:%(lineno)d] %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
filename=logfile,
#level=10,
filemode='a')
logging.info("This is a info.\n")
logging.warn("This is a warning.\n")
logging.error("This is a error.\n")
#logging.log("This is a log. \n\n")
logging.debug("This is a debug. \n\n")
logging.critical("This is a critical \n\n\n")
logging.info("now time is {time}".format(time=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))))
logging.info("normal type , today is {today} , yesterday is {yesterday} , tomorrow is {tommorrow} .".format(today=today,yesterday=yesterday,tommorrow=tomorrow))
logging.info("nyr style , today is {today} , yesterday is {yesterday} , tommrrow is {tommorrow} .".format(today=Today_nyr,yesterday=Yesterday_nyr,tommorrow=Tomorrow_nyr))
###从一个目录中,取出所有文件名进行循环
from subprocess import call
File_Dir = "/tmp"
File_List = os.listdir(File_Dir)
for f in File_List:
if( f[0] == '.' ):
continue
else:
logging.info("{filename}".format(filename=f))
###读取一个文件的多行,进行循环
#文件读取方法一:
file = open("/tmp/3.txt")
while 1:
line = file.readline()
if not line:
break
logging.info("this line is :{line}".format(line=line))
#文件读取方法二:
import fileinput
for line in fileinput.input("/tmp/3.txt"):
logging.info("this line is :{line} .".format(line=line))
#文件读取方法三:
file = open("/tmp/3.txt")
for line in file:
logging.info("this line is :{line} .".format(line=line))
###获取一个shell命令执行结果,进行循环
#获取命令方法一:
import subprocess
shell_cmd = "df -h | awk '{print $1}'"
p = subprocess.Popen("{cmd}".format(cmd=shell_cmd), shell=True, stdout=subprocess.PIPE)
out = p.stdout.readlines()
for line in out:
print line.strip()
logging.info(" file system is :{line} .".format(line=line.strip()))
#获取命令方法二:
for line in subprocess.Popen("df -h | awk '{print $1}'",shell=True,stdout=subprocess.PIPE).stdout.readlines():
print line.strip()
logging.info(" file system is :{line} .".format(line=line.strip()))
上面的脚本,可使用 python 3.py 直接执行。
脚本执行结果如下: