One Hundred and Seventy

Python modules commonly used

One, wrapped

1.1 What is the package

Package is a form, is essentially a file containing .py files.

1.2 Why use package

The first version of the module is only 10 function, but in the future when the extended version, module name and usage should be best not to change, but this is only for user-friendly, and because the extended version, files increases, the module designers management module, maintenance will be more complicated, so we can use the package to extend the function of the module.

1.3 How to use package

1.3.1 modules and packages

Import module three things happen:

  1. Create a namespace package
  2. Py file execution, the execution name generated in the process is stored in the namespace.
  3. Aaa get a name in the current executable file, aaa is pointing package namespace

Importing package three things happen:

  1. Create a namespace package
  2. Since the package is a folder, you can not execute the package, so .py files in the package is executed, the execution name generated in the process is stored in the package namespace (namespace name that is stored in the package are from .py)
  3. Aaa get a name in the current executable file, aaa is pointing package namespace

Introducing the package is introduced in the package .py, and may be introduced into the following two ways:

  1. import ...
  2. from ... import...

1.3.2 Expansion Module function

If we want to extend aaa.py modules need to create a catalog file aaa, and delete aaa.py file, aaa.py modified to m1.py and m2.py two files, make use of the module function does not change .

1.3.3 modify _init _.py file

# aaa/.py

func1 = 111
func2 = 222
func3 = 333
func4 = 444
func5 = 555
func6 = 66

Since __init__.pydefined func1, so we can import func1 in run.py file, but this is not what we want func1 func1, it is necessary to modify __init__.pythe file, and because the environment variable is not executable file run.py aaa, therefore directly import import m1 will complain, so use from import.

# aaa/.py

from aaa.m1 import func1
from aaa.m2 import func2
# run.py

import aaa


print(aaa.func1())
print(aaa.func2())

1.3.4 introduced into the bag

aaa.bbb pointing inside the folder aaa bbb package, if we need to import bbb this package.

# bbb/.py

from aaa import bbb
# run.py

import aaa


print(aaa.bbb)

1.3.5 introduced into packet module

# bbb/.py

from aaa.bbb import m3
# run.py

import aaa


aaa.bbb.m3

1.4 Considerations

  1. All files in the package are imported using, instead of being run directly
  2. Introduced between the inner bag module can use absolute introduced (in the root directory as a reference packet) relative introduced (in the current directory where the module is introduced as a reference), recommended relative import
  3. When the file is executable file, not a relative import syntax, and only when the file is imported as a module within the file within the file in order to use the syntax of relative imports
  4. Those who a little while importing the left point must be a package import aaa.bbb.m3.f3error

Second, the common module

2.1 time module

time module: supports three different types of time, it can be switched between the various forms of time.

  1. Timestamp: From January 1970 00:00:00 1st to partial amounts, in seconds now
import time
print(time.time())

1565951647.1459594
  1. Formatting time: time expressed as a string format
import time
print(time.strftime('%Y-%m-%d %X'))

2019-08-16 18:38:09
  1. Structured time: struct_time tuple total of nine elements were asked date when minutes and seconds Sunday daylight saving time.
import time
print(time.localtime())
print(time.gmtime())

time.struct_time(tm_year=2019, tm_mon=8, tm_mday=16, tm_hour=18, tm_min=46, tm_sec=37, tm_wday=4, tm_yday=228, tm_isdst=0)
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=16, tm_hour=10, tm_min=46, tm_sec=37, tm_wday=4, tm_yday=228, tm_isdst=0)
  1. Three kinds of time format conversion
import time
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()))# 时间戳转结构化时间
  1. time.sleep(n)

2.2 datatime module

datetime module can be seen as add or subtract modules.

  1. current time
import datetime
print(datetime.datetime.now())

2019-08-16 18:58:58.357782
  1. Increase Decrease Time (days)
import datetime
print(datetime.datetime.now()+datetime.timedelta(2))

2019-08-18 19:03:59.046982
  1. Increases to reduce the time (hours, minutes)
import datetime
print(datetime.datetime.now()+datetime.timedelta(hours=12))

2019-08-17 07:06:07.106167
  1. Instead of time
import datetime
print(datetime.datetime.now().replace(hour = 10,second = 5,year = 1))

0001-08-16 10:11:05.001715

2.3 os module

os module is responsible for programs interact with the operating system, provides the interface to access the operating system, used for file handling.

import os

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

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

# # *************(经常用到)
res = os.listdir(r'D:\...)  # 列出所有文件
print(res)

 __file__只有pychamr才提供,python本身不支持
print('os.path.abspath(__file__):',os.path.abspath(__file__))  # 支持不同的平台(windows,ios,andirod,linux,unix)
                 
 print('__file__:',__file__)

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


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


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

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

2.4 sys module

Responsible for interacting with the python interpreter program sys module, it provides a range of functions and variables to control when running python environment.

import  sys
print(sys.argv)  # 接收参数(用cmd执行文件时运行才有效)
print(sys.modules) #返回系统导入的模块字段,key是模块名,value是模块

2.5 json and pickle module

jason pickle and are serialized manner, the object is to remove the serialization process can be stored into or transferred from memory.

Serialization advantages:

  1. Persist status: Memory is not permanently stored data, when the program runs for some time, we power down or restart the program, in-memory data on the program for some time before the (structured) have been cleared. But before power off or restart the program that are currently all the data in memory are saved (saved to a file) to perform data can be loaded from the file before the program to the next, and then continue, which is serialized .
  2. Cross-platform data exchange: not only the contents of the serialized write serialization disk, you can also transmitted over the network to another machine, if the two sides agreed to send and receive good practical one sequence of the format, then it broke platform / language difference limit brought achieve a cross-platform data exchange.

Json serialization is not unique to python, json serialization in java and other languages ​​will be involved, so use json serialization can achieve the purpose of cross-platform data transmission.

import json
dic = {'a': 1, 'b': 'abc', 'c': None}
data = json.dumps(dic)  # 序列化到内存中
print(data,type(data))  # 单引号全部变成双引号
data = json.loads(data)  # 从内存中获取json串
print(data,type(data))

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

Pickle serialization and unique serialization problem with all other programming languages, it can only be used Python, and may be different versions of Python are not compatible with each other, therefore, can only be saved unimportant data Pickle, that is not successful deserialized it does not matter. But the benefits of pickle that can store all data types in Python, including objects, json can not.

2.6 hashlib module and hmac

a hash algorithm that accepts incoming content, after calculating the hash value string obtained.

hash value features:

  1. As long as the incoming content, hash value obtained as clear text password can be used to transport non-cryptographic checksum.

  2. Value can not be returned by the hash solution into content that can guarantee the security of non-clear-text passwords.

  3. As long as the same hash algorithm used, regardless of how the contents of the verification, the hash value of a fixed length to obtain, hashing can be used for text.

    hashlib can become a fixed character string numbers, the same result as the hash of the string and having a superposition.

    import hashlib
    
    m = hashlib.md5()  # 固定的写法
    m.update(b'123456')
    print(m.hexdigest())
    
    e10adc3949ba59abbe56e057f20f883e

    hmac Module: encryption password to be salt, equivalent to the cryptographic key is added.

    import hmac
    
    m = hmac.new(b'abc')  # 加盐
    m.update(b'123456')
    print(m.hexdigest())
    
    8c7498982f41b93eb0ce8216b48ba21d

2.7 logging module

Guess you like

Origin www.cnblogs.com/tangceng/p/11366072.html