常用模块

random

import random

l = [1,2,3,4,5,6]
l1 = random.shuffle(l)      #将序列的所有元素随机排序。

print (l)


#生成一个6位字母的随机验证码

import random
li = []
for num in range(6):
    i = random.randrange(65, 91)
    print(i)
    c = chr(i)          #chr()函数用一个范围在range(256)内的(就是0~255)整数作参数,返回一个对应的字符。
    li.append(c)
re = "".join(li)      #拼接
print (re)


#生成6位字母数字随机验证码 import random li = [] for i in range(6): r = random.randrange(0,5) ##生成随机数, if r == 3 or r == 4: d = random.randrange(0, 10) li.append(str(d)) ###由于下面要 join,而join只能是字符串,所以加str else: d = random.randrange(65,91) c = chr(d) li.append(c) re = "".join(li) print (re)

####
import random
print (random.choice("adasfewewdd")) #从字符串中随机选择一个

os模块

os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
os.curdir  返回当前目录: ('.')
os.pardir  获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2')    可生成多层递归目录
os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()  删除一个文件
os.rename("oldname","newname")  重命名文件/目录
os.stat('path/filename')  获取文件/目录信息
os.sep    输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep    输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep    输出用于分割文件路径的字符串
os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")  运行shell命令,直接显示
os.environ  获取系统环境变量
os.path.abspath(path)  返回path规范化的绝对路径
os.path.split(path)  将path分割成目录和文件名二元组返回
os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path)  返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path)  如果path是绝对路径,返回True
os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间

time模块

print (time.ctime())    ###当前系统时间
print (time.time())
t1 = time.localtime(time.time())       #本地时间
print (time.localtime(time.time()))
print ("{year}-{month}-{hour}".format(year=t1.tm_year,month=t1.tm_mon,hour=t1.tm_hour))   #自定义时间
print (time.mktime())    ###将时间对象转化为时间戳
time.sleep(4) ####延迟4秒

print (time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))    ### 按指定的时间格式输出
print (time.strptime("2016/01/01","%Y/%m/%d"))    ####将字符串格式转换成struct time 格式

import time
print (time.localtime())
打印结果:

time.struct_time(tm_year=2017, tm_mon=5, tm_mday=7, tm_hour=12, tm_min=39, tm_sec=25, tm_wday=6, tm_yday=127, tm_isdst=0)

###打印时间戳
print (time.time())

打印结果:
1494132051.0743935

##打印格式化的时间(元组)
print (time.gmtime())

打印结果:
time.struct_time(tm_year=2017, tm_mon=5, tm_mday=7, tm_hour=4, tm_min=42, tm_sec=26, tm_wday=6, tm_yday=127, tm_isdst=0)


import time print (time.gmtime()) ###时间戳转换为元组传递当前时间元组(标准时间) print (time.localtime()) ###时间戳转换为元组传递本地时间到元组形式(本地时间) x = time.localtime() print (x.tm_year,x.tm_mon,x.tm_mday,x.tm_hour) ###单独打印时间 打印结果: time.struct_time(tm_year=2017, tm_mon=5, tm_mday=7, tm_hour=5, tm_min=53, tm_sec=20, tm_wday=6, tm_yday=127, tm_isdst=0) time.struct_time(tm_year=2017, tm_mon=5, tm_mday=7, tm_hour=13, tm_min=53, tm_sec=20, tm_wday=6, tm_yday=127, tm_isdst=0) 2017 5 7 13

mktime()
####将元组转换为时间戳 x = time.localtime() print (x.tm_year,x.tm_mon,x.tm_mday,x.tm_hour) print (time.mktime(x)) 打印结果: 2017 5 7 13 1494136624.0 元组转化为字符串 (strftime()) 语法:strftime(format,struct_time) -----> 转化为字符串 x = time.localtime() print (x) print (time.strftime("%Y-%m-%d %H:%M:%S",x)) 打印结果: time.struct_time(tm_year=2017, tm_mon=5, tm_mday=7, tm_hour=14, tm_min=14, tm_sec=56, tm_wday=6, tm_yday=127, tm_isdst=0) 2017-05-07 14:14:56 字符串时间转化为元组:(strptime) 语法:strptime("格式化字符串""时间格式") ------> 转化为元组 print (time.strptime('2017-08-20 17:12:12','%Y-%m-%d %H:%M:%S')) 打印结果: time.struct_time(tm_year=2017, tm_mon=8, tm_mday=20, tm_hour=17, tm_min=12, tm_sec=12, tm_wday=6, tm_yday=232, tm_isdst=-1) print (time.asctime()) ##接收一个元组作为参数 ctime()       ####接收一个时间戳作为参数 打印结果: Sun May 7 14:52:46 2017 datetime模块 import datetime print (datetime.datetime.now()) ####获取当前时间 print (datetime.datetime.now()+datetime.timedelta(3)) ####获取几天前后几天后时间(3为3天后时间,-3为3天前时间# ) print (datetime.datetime.now()+datetime.timedelta(hours=3)) ####获取几天前后几天后时间(3为3小时后时间,-3为3小时前时间# ) print (datetime.date.today()) ###打印当前时间 print (datetime.date.fromtimestamp(time.time()))## print (datetime.datetime.now()) ####打印详细当前时间 print (datetime.datetime.now() + datetime.timedelta(days=10)) ###比现在加10天 print (datetime.datetime.now() + datetime.timedelta(days=-10)) ###比现在减10天 print (datetime.datetime.now() - datetime.timedelta(days=10)) ###比现在减10天 print (datetime.datetime.now() + datetime.timedelta(hours=10)) ###比现在加10小时 current_time = datetime.datetime.now() print (current_time.replace(2015,5)) ####回到某一天 print (datetime.datetime.strptime('21/11/06 16:40','%y/%m/%d %H:%M')) 结果: 2021-11-06 16:40:00

hashlib

import hashlib

import base64

#####base64 加密与解密#########
加密
a = '[email protected]:LAVION@2017'
jiami = base64.b64encode(a)
print  jiami

#################解密#############333
s = 'Z2FveGluamllQGxhdmlvbi5jb20uY246TEFWSU9OQDIwMTc='
decode = base64.b64decode(s)
print decode.decode()

#########md5加盐加密#################
hash = hashlib.md5(bytes('57136421',encoding='utf-8'))    ####md5加盐
hash.update(bytes('123456',encoding='utf-8'))              ### md5加密
result = hash.hexdigest()
print (result)

# ######## md5 ########
 
hash = hashlib.md5()
hash.update('admin')
print(hash.hexdigest())
 
# ######## sha1 ########
 
hash = hashlib.sha1()
hash.update('admin')
print(hash.hexdigest())
 
# ######## sha256 ########
 
hash = hashlib.sha256()
hash.update('admin')
print(hash.hexdigest())
 
 
# ######## sha384 ########
 
hash = hashlib.sha384()
hash.update('admin')
print(hash.hexdigest())
 
# ######## sha512 ########
 
hash = hashlib.sha512()
hash.update('admin')
print(hash.hexdigest())

subprocess

#!/usr/bin/env python
#-*-coding:utf-8 -*-

import subprocess

obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/')    ##在home目录下创建t3文件夹
obj1 = subprocess.Popen(['mkdir','t2'])             ##在当前目录创建t2 文件夹
obj2 = subprocess.Popen(['mkdir','t3'],cwd='/root/')             ##在root目录创建t3文件夹

  terminate() 杀掉所启动进程
  communicate() 等待任务结束
  stdin 标准输入
  stdout 标准输出
  stderr 标准错误

shutil

shutil.copyfile(''源名称",'目的名称')            ###拷贝文件
shutil.copy(''源名称",'目的名称')            ###拷贝文件和权限
shutil.copytree(”src“,"dest")                        ###递归的去拷贝文件
shutil.make_archive(base_name,format(zip,tar..),要压缩的文件)

sys

sys.argv           命令行参数List,第一个元素是程序本身路径
sys.exit(n)        退出程序,正常退出时exit(0)
sys.version        获取Python解释程序的版本信息
sys.maxint         最大的Int值
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       返回操作系统平台名称
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]

xml

样例数据

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
View Code

处理脚本及打印结果

import xml.etree.cElementTree as  et

tree = et.parse("aaaa")

root = tree.getroot()

for c in root:
        print (c.tag,c.attrib)
        for i in c:
            print (i.tag,i.text)

for d in root.iter("year"):
    print (d.tag,d.text)

打印结果:
country {'name': 'Liechtenstein'}
rank 2
year 2008
gdppc 141100
neighbor None
neighbor None
country {'name': 'Singapore'}
rank 5
year 2011
gdppc 59900
neighbor None
country {'name': 'Panama'}
rank 69
year 2011
gdppc 13600
neighbor None
neighbor None
year 2008
year 2011
year 2011

xml操作

import xml.etree.ElementTree as ET

tree = ET.parse("xmltest.xml")
root = tree.getroot()

# 修改
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)
    node.set("updated", "yes")

tree.write("xmltest.xml")

# 删除node
for country in root.findall('country'):
    rank = int(country.find('rank').text)
    if rank > 50:
        root.remove(country)

tree.write('output.xml') 


创建xml:

import xml.etree.ElementTree as ET

new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
age = ET.SubElement(name, "age", attrib={"checked": "no"})
sex = ET.SubElement(name, "sex")
sex.text = '33'
name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age = ET.SubElement(name2, "age")
age.text = '19'

et = ET.ElementTree(new_xml)              # 生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True)

ET.dump(new_xml)              # 打印生成的格式

configparser

import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'  # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
    config.write(configfile)


生成的结果为:

[DEFAULT]
compression = yes
compressionlevel = 9
serveraliveinterval = 45
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
host port = 50022
forwardx11 = no


读:

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']: print(key)
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'

logging模块

两种形式:打印到屏幕;写入到文件

日志级别

#默认的日志级别为warnning 

debug()----》info()-----》warning(),-----》error() ------》 critical()

如果设置日志级别为debug,则可打印所有级别日志
如果设置日志级别为warning,则只打印warning error critical 三个级别的日志

示例:

import logging

logging.basicConfig(filename='example.log',level=logging.INFO)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

打印结果(设置的日志级别为info,所以只打印info和warning

灵活设置日志(仅限写入文件)

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='/tmp/test.log',  
                    filemode='w')                                            #文件打开方式
#stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open('test.log','w')),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
logging.debug(
'debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
#打印结果 cat
/tmp/test.log Mon, 05 May 2014 16:29:53 test_logging.py[line:9] DEBUG debug message Mon, 05 May 2014 16:29:53 test_logging.py[line:10] INFO info message Mon, 05 May 2014 16:29:53 test_logging.py[line:11] WARNING warning message Mon, 05 May 2014 16:29:53 test_logging.py[line:12] ERROR error message Mon, 05 May 2014 16:29:53 test_logging.py[line:13] CRITICAL critical message

format参数中的格式化串

%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息

logger对象

import logging

#创建logger对象 logger
= logging.getLogger()
# 创建一个handler,用于写入日志文件 fh = logging.FileHandler('test.log') # 再创建一个handler,用于输出到控制台 ch = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')    #格式对象,默认日志级别为warning
#获取格式对象 fh.setFormatter(formatter) ch.setFormatter(formatter)
logger.addHandler(fh) #logger对象可以添加多个fh和ch对象
logger.addHandler(ch)


#另一种写法
fh = logging.FileHandler('test.log')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger1=logging.Logger("file_name",level=logging.debug)
logger1.addHandler(fh)

 logger.debug('logger debug message')
 logger.info('logger info message')
 logger.warning('logger warning message')
 logger.error('logger error message')
 logger.critical('logger critical message')

logging库提供了多个组件:Logger、Handler、Filter、Formatter。Logger对象提供应用程序可直接使用的接口,Handler发送日志到适当的目的地,Filter提供了过滤日志信息的方法,Formatter指定日志显示格式。

filter

   限制只有满足过滤规则的日志才会输出。
        比如我们定义了filter = logging.Filter('a.b.c'),并将这个Filter添加到了一个Handler上,则使用该Handler的Logger中只有名字带  a.b.c前缀的Logger才能输出其日志。

import logging

logger = logging.getLogger()
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler('test.log')

# 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

fh.setFormatter(formatter)
ch.setFormatter(formatter)

# 定义一个filter
filter = logging.Filter('mylogger')
fh.addFilter(filter)
ch.addFilter(filter)

# logger.addFilter(filter)
logger.addHandler(fh)
logger.addHandler(ch)

logger.setLevel(logging.DEBUG)

应用

import os
import time
import logging
from config import settings


def get_logger(card_num, struct_time):

    if struct_time.tm_mday < 23:
        file_name = "%s_%s_%d" %(struct_time.tm_year, struct_time.tm_mon, 22)
    else:
        file_name = "%s_%s_%d" %(struct_time.tm_year, struct_time.tm_mon+1, 22)

    file_handler = logging.FileHandler(
        os.path.join(settings.USER_DIR_FOLDER, card_num, 'record', file_name),
        encoding='utf-8'
    )
    fmt = logging.Formatter(fmt="%(asctime)s :  %(message)s")
    file_handler.setFormatter(fmt)

    logger1 = logging.Logger('user_logger', level=logging.INFO)
    logger1.addHandler(file_handler)
    return logger1

猜你喜欢

转载自www.cnblogs.com/FRESHMANS/p/8783531.html