[0816 | Day17] module introduction

package

A module package, but also a folder (have to contain __init__.pythe file).

A, one packet

Day 17

  • m1
    • __init__.py # To run m2.py/m3.py, input from m1 (parent file) .m2 (Run the file) /m1.m3 import *
    • m3.py
    • m4.py
  • m2.py

1. Note: m2.py can find m1.py, guide package is to import init, the package __init__.pycan only start importing from the package name, the environment variable to execute the file as a reference.

2. Note: in __init__.pythe input from m1.m2 import f1 and from .m2 import f2, the former is an absolute path, the latter (only referenced in the package) relative path.

Second, two-package

Day 17

  • m1
    • a
      • __init__.py # To run m5.py, or input from ..a.m5 import * from mam5 import *
      • m5.py
    • __init__.py
    • m3.py
    • m4.py
  • __init__.py
  • m2.py

1. Note: the current directory '..' parent directory '.'.

time module

Supports three different forms of time, you can switch between different forms of time.

First, the time stamp

import time

print(time.time())  

# 1565922341.6068554

Second, the time format

#year month day X

print(time.strftime('%Y_%m_%d %X'))  

# 2019_08_16 10:26:36

Third, the structure of the time

print(time.localtime())  # 当地时间(中国)

print(time.gmtime())  # 标准时间

Fourth, the three kinds of time format conversion

# 结构化时间转格式化时间
print(time.strftime('%Y-%m-%d %X', time.localtime()))

# 格式化时间转结构化时间
print(time.strptime('2019-08-16 10:30:44', '%Y-%m-%d %X'))

# 结构化时间转时间戳
print(time.mktime(time.localtime()))

# 时间戳转结构化时间
print(time.localtime(time.time()))

# 重点
time.time()
time.sleep(2)

datetime module

Modification time.

import datetime

print(datetime.datetime.now())  

# 打印时间
now = datetime.datetime.now()

print(now+datetime.timedelta(3))  # 默认+3天
print(now+datetime.timedelta(hours=3))  # 3小时
print(now+datetime.timedelta(minutes=3))  # 3分钟
print(now+datetime.timedelta(seconds=3))  # 3分钟

print(now.replace(year=1900))

os module

Interact with the operating system, you can manipulate files.

import os

os.getcwd() # 获取当前文件目录

os.mkdir('m2') # 创建一个文件夹
os.rmdir('m2')  # 删除文件夹

# *************(经常用到)
os.listdir(r'D:\上海Python11期视频\python11期视频\day 17')  # 列出所有文件

os.rename('test.py','test1.py')
os.remove('test1.py')


# __file__只有pycharm才提供,python本身不支持,支持不同的平台(windows,ios,andirod,linux,unix)

os.path.abspath(__file__) #返回path规范化的绝对路径

os.path.exists('01 包.py') # 文件不存在False,存在True


os.path.isfile('01 包.py') # 是否为文件
os.path.isdir('01 包.py') # 是否为文件夹


# ********(经常使用)
# 支持不同的平台(windows,ios,andirod,linux,unix)
os.path.join(r'D:\上海Python11期视频\python11期视频\day 17\m1\bbb','m5.py') # 拼接文件路径
os.path.join(r'D:\上海Python11期视频\python11期视频\day 17\m1\bbb','m5','test.py') # 拼接文件路径


# ******* (经常使用)
os.path.abspath(__file__)
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


import os
g = os.walk(r'D:\上海Python11期视频\python11期视频\day 17')  
# 返回三个值:第一个值是路径;第二个值是路径下的文件夹;第三个值是路径下的文件
for i in g:
    print(i)
    
    
# 计算代码函数

##第一种(只计算单个文件的代码)
import os

def count_code(path):
    count = 0
    flag = True
    if os.path.isfile(path):
        path_list = path.split('.')
        if path_list[-1] == 'py':
            with open(path,'r',encoding='utf8') as fr:
                for line in fr:
                    #判断引号注释首行,确认后返回False
                    if  (line.startswith('\'\'\'') or line.startswith('\"\"\"')) and flag:
                        flag = False
                        continue
                    #判断引号注释末行,确认后返回True
                    elif (line.startswith('\'\'\'') or line.startswith('\"\"\"')) and not flag:
                        flag = True
                        continue
                    # 判断是否注释
                    elif line.startswith('#') and flag:
                        continue
                    #判断是否空行
                    elif line == '\n' and flag:
                        continue
                    elif flag:
                        count += 1
                        continue
                print(f'你的文件有{count}行代码。')
        else:
            print('该对象不是文件!!!')

count_code(r'D:\fxyadela\作业\猜年龄\猜年龄(函数版).py')


##第二种(计算文件夹下所有py文件的代码行数)

sys module

Interaction with the Python interpreter

import  sys

print(sys.path)
print(sys.argv)  # 接收参数(用cmd执行文件时运行才有效)
print(sys.modules)  #获取内置模块

json module

A program written in python, using java to write a program, the program requires two exchanges between the data, a predetermined common data types of languages, namely json string.

Serialization: become json string ---> dump (file) from a python dictionary (the most common)

Deserialize: json into python string from the dictionary (the most common) ---> load

import json

dic = {'a': 1, 'b': 'kv', 'c': None}

data = json.dumps(dic)  # 序列化到内存中
print(data,type(data))  # 单引号全部变成双引号

#{"a": 1, "b": "abc", "c": null} 
#<class 'str'>

data = json.loads(data)  # 从内存中获取json串
print(data,type(data))

#{'a': 1, 'b': 'abc', 'c': None} 
#<class 'dict'>

with open('test.json','w',encoding='utf8') as fw:
    json.dump(dic,fw)

with open(f'{"test"}.json','r',encoding='utf8') as fr:
    data = json.load(fr)
    print(data)
    
#{'a': 1, 'b': 'abc', 'c': None}   
    
    

pickle module

Python can serialize all objects (data types), but not cross-platform.

dic = {'a': 1, 'b': 'abc', 'c': None}

def func():
    x = 3
    print(x)

import pickle

with open('test.pkl','wb') as fw:  #pickle模块下,文件为二进制形式,乱码无法读取
     pickle.dump(func,fw)   #将func写入test.pkl文件中


#运行这一步时关闭上一个写入文件
with open('test.pkl', 'rb') as fr:
    data = pickle.load(fr)   #data = func
    data()  #data() = func()
    print(data)  #print(3) = 3

hashlib module

Password encryption: No matter what you throw the string, he will return a string of fixed-length string.

import hashlib

#第一种
m = hashlib.md5()  # 固定的写法
m.update(b'123456')
# m.update(b'hello') #‘123456'可以替换自己想写的东西
print(m.hexdigest())

# e10adc3949ba59abbe56e057f20f883e

#第二种
m = hashlib.md5()  # 固定的写法
m.update(b'123')
m.update(b'456') 
print(m.hexdigest())

# e10adc3949ba59abbe56e057f20f883e

1. Note: string becomes fixed

2. Note: As the result of the same string hashing

3. Note: superposition

hmac module

Password encryption and tightened.

import hmac

m = hmac.new(b'abc')  # 第一层密码
m.update(b'123456')  #第二层密码

print(m.hexdigest())

# abc 123 456 --> 8c7498982f41b93eb0ce8216b48ba21d
# abc 123456 --> 8c7498982f41b93eb0ce8216b48ba21d
# a 1234556 --> 3e391a1d7bf574cec59679244a2904fe
# 123456 --> 8c7498982f41b93eb0ce8216b48ba21d
# 123456 --> 8c7498982f41b93eb0ce8216b48ba21d

The first layer Password: abc

  • b‘123’ b'456' == b'123456'

The first layer password: a.

  • b'123' b'456' == b'123456';

Note: The first layer of the password is not identical, the second layer code, a different final result, only the same result as the first layer under the same password.

logging module

Log.

A, V2

Simply log application can not specify character encoding, can only print to file.

import logging

# 日志的基本配置

logging.basicConfig(filename = 'access.log',
                    format = '%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
                    datefmt = '%Y-%m-%d %H:%M:%S %p',
                    level = 10  #logging.info
                    #filemode = 'w'  添加这一项利用只读特点,只更新最新消息)

logging.debug('调试信息')  # 10
logging.info('正常信息')  # 20
logging.warning('警告信息')  # 30
logging.error('报错信息')  # 40
logging.critical('严重错误信息')  # 50

May logging.basicConfig () function can be changed by the logging module specific parameters default behavior parameters are available:

filename: Creating FiledHandler with the specified file name (will explain in detail the concepts behind the handler), so logs are stored in the specified file.
filemode: File Open, this parameter is specified in the filename, the default value "a" may also be designated as "w".
format: log handler specified display format.
datefmt: specify the date and time format.
level: Set rootlogger (behind will explain specific concepts) log level
stream: StreamHandler created with the specified stream. You can specify output to sys.stderr, sys.stdout or file, the default is sys.stderr. If both lists the filename and stream two parameters, the stream parameter is ignored.

the format parameter string format may be used:

% (name) s Logger names
% (levelno) s digital form log level
% (levelname) s in text form log level
% (pathname) s call to the full path name of the module log output function, may not be
% (filename) s calling module log output function filename
% (Module1) s calling module name log output function
% (funcName) s calling a function for a log output function of
% (lineno) d call statement log output function where the line
% (created) f the current time, represented by a standard floating point representation UNIX time
, the number of milliseconds since Logger created at% (relativeCreated) d output log information
% (asctime) s current time string. The default format is "2003-07-0816: 49: 45,896." Milliseconds after the comma
% (thread) d thread ID. It may not have
% (threadName) s thread name. May not be
d Process ID% (process). May not
% (message) s user output message

Two, V3

logging module contains four roles: logger, Filter, Formatter objects, Handler

  1. Logger : Object generated logs
  2. The Filter : Object filtering logs
  3. Formatter : You can customize different log format object, and then bind to different Handler object using, in order to control the different log format Handler
  4. Handler : receiving a log and then controls the printing to different places, FileHandler used to print to a file, StreamHandler for printing to the terminal
# 1. 生成一个logger对象
logger = logging.getLogger('nick')

# 2. 生成格式
formmater1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                               datefmt='%Y-%m-%d %H:%M:%S %p',)
formmater2 = logging.Formatter('%(asctime)s :  %(message)s',
                               datefmt='%Y-%m-%d %H:%M:%S %p',)
formmater3 = logging.Formatter('%(name)s %(message)s',)

# 3. 生成一个文件对象
h1 = logging.FileHandler('h1.log')
h2 = logging.FileHandler('h2.log')
sm = logging.StreamHandler()


# 4. 文件绑定格式
h1.setFormatter(formmater1)
h2.setFormatter(formmater2)
sm.setFormatter(formmater3)


# 5. 绑定文件
logger.addHandler(h1)
logger.addHandler(h2)
logger.addHandler(sm)

# 6. 控制级别
logger.level = 50

# 7. 使用
logger.debug('调试信息')  # 10
logger.info('正常信息')  # 20
logger.warning('警告信息')  # 30
logger.error('报错信息')  # 40
logger.critical('严重错误信息')  # 50

Guess you like

Origin www.cnblogs.com/fxyadela/p/11366053.html