各种模块
1.时间模块
import time # 调用
time.time()  # 从1970年1月1日开始算 以秒计算  **********
time.clock() # cpu 工作的时间段
time.sleep(2)   # 暂停时间多少秒    ************
print(time.gmtime())   # time.struct_time(tm_year=2016, tm_mon=9, tm_mday=8, tm_hour=10, tm_min=32, tm_sec=2, tm_wday=3, tm_yday=252, tm_isdst=0) 格林尼治时间
time.localtime()   # 本地时间
a = time.strftime("%Y-%m-%d",time.localtime())          # X表示小时的默认显示 H S M 时分秒 *******        ************
print(a)
a = time.strptime("2016-09-08","%Y-%m-%d")  # 转换成结构化时间
print(a.tm_year)                                 # 找到年
time.ctime()                      # 规定好的本地时间
time.ctime(2222222222)            # 将这些秒转换成时间加到utc上
time.mktime(time.localtime())        # 将一个结构化时间转换成时间戳
import datetime
print(datetime.datetime.now())        #2016-09-08 19:07:37.217636

2.随机模块
import random
print(random.random())             # 0-1 之间的数据
print(random.randint(1,10))         # 可规定范围
random.choice("kdjgicg")            # 随机选择一个字母
print(random.sample([1,2,3,4,5],2))    # 随机选择多个
print(random.randrange(1,10))                # 范围随机 不会选到10
2.1生成验证码
def creat_jihema(): jihema = "" for i in range(6): add = random.choice((str(random.randrange(10)),chr(random.randint(65,90)))) jihema = "".join([jihema,add]) return jihema
3.os模块
import os
os.getcwd()    # 获得当前目录
os.chdir("c\user")  # 改变当前目录
os.curdir        # 返回当前目录
os.pardir        # 返回父目录
os.makedirs("a\\b\\c")  # 在当前目录下创建多级的dir
os.removedirs("a\\b\\c")  # 无内容时 就会被删除  从最后一级开始删除 有文件时就会停下
os.mkdir("day4\\gaga")           # 当前目录创建一个   也可以在已有的路径下创建
os.rmdir("day4\\gaga")           # 必须为空  并且删除一个
os.listdir("day4")                #
"abc\nefg"            # 会换行
"r "abc\nefg"  "         # 不换行
os.remove("info")           # 只能删除文件  不能删文件夹
os.rename("info","gaga")   # 原名子 新名字
g = os.stat(".\\info")      # os.stat_result(st_mode=33206, st_ino=111182615800709967, st_dev=877244742, st_nlink=1, st_uid=0, st_gid=0, st_size=120, st_atime=1473311335, st_mtime=1473311335, st_ctime=1473299253)
print(g)                     # g.st_size 文件大小
print(os.sep )                 # 打印 反斜杠(linux下为斜杠) 跨平台使用时  变量接收一下s 代替当前系统的dir分隔符
os.linesep                     # 同上
os.pathsep                     # 同上 路径的分隔符 .\d\dfe\f ; df\ef
os.system("dir")                #执行shell命令
os.environ                      # 获取环境变量
os.path.abspath(".\info")      # 获取绝对路径
os.path.split(".\info")          # 分成一个元组 一个是路径 一个是文件名
os.path.dirname("C:\Users\Shince\PycharmProjects\Deanerys\week4\day4\模块.py") # 提取文件夹名字 day4的绝对路径
os.path.basename("C:\Users\Shince\PycharmProjects\Deanerys\week4\day4\模块.py") # 模块.py
os.path.join(["C:\Users\Shince\PycharmProjects\Deanerys\week4\day4\模块.py","path"])  # 路径拼接
os.path.getmtime("C:\Users\Shince\PycharmProjects\Deanerys\week4\day4\模块.py") # 得到修改时间
4.sys模块
import sys
sys.argv                           # 通过传入参数控制程序的执行
if sys.argv[1]=="name":
    print("ok")                       #  执行时候 cmd python 模块.py name
sys.exit()                              # = exit()
print(sys.path)                 # 展示模块搜寻路径
sys.path.append("abspath")             # 添加到搜寻路径中  为了找自己模块
import os                        # 方便多平台的使用
if sys.platform == "win32":          # 显示当前系统
    os.system("dir")              # 运行dir
else:
    os.system("ls")                # 若是linux  执行ls
5.hashlib模块
import hashlib                          # 密码转化
m= hashlib.md5()                    # MD5是byte编码
print(m)
m.update("gaga".encode("utf8"))   # gaga 是万国码
print(m.hexdigest())                 #811584043b844704c9bb9a6e99dd05d3  转码成功 通过md5算法 hex 是16进制  digest是将bit转换成str
m.update("fafa")                      # 再次的更新会将 gagafafa 加密
hashlib.sha256()                      # 同理同上加密方式 更加复杂
6.logging模块
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='test.log', filemode='w') # 写到文件中 模式为A好 logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
可见在logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有
filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
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用户输出的消息
7.logger双显示
import logging
logger = logging.getLogger()                                     # 得到logger对象
f = logging.FileHandler("test.log","a",encoding="utf8")      # 创建文件显示对象
c = logging.StreamHandler()                                    # 创建屏幕流显示
setf = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # 设置日志格式
f.setFormatter(setf)                                                  # 将格式给f
c.setFormatter(setf)                                                 # 在给c
logger.addHandler(f)                                               # f 给logger
logger.addHandler(c)                                              # c 也 给logger
logger.warning("嘎嘎")                                           # 生成日志
8.config模块
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)
上面是写入
### 读
import configparser
config = configparser.ConfigParser()
config.read('example.ini')           #关联配置文件
print(config.sections())               # 查看第一层key
for key in config['bitbucket.org']:
    print(key)                        # default下的key也会打印 默认打印
##### 修改
config.set('bitbucket.org',"user","ccc")
config.write(open("example.ini" "w"))
 
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号