Common Python modules: time, random, os, sys, hashlib, logging, serialization

Common modules

1. Time module ***
2. Random module *****
3. os module
4. sys module
5. Serialization module *****
6. hashlib module ****
7. logging module **** *

Time module:

#Import and common methods
import time
1.time.sleep (secs)
(thread) Delay the specified time to run. The unit is second
2. time.time () Get the current timestamp

There are three types of time:

  • Timestamp time, float data type, Greenwich time, time for machine
  • Formatting time, str data type (string time), time for people to see
  • Structured time, time object, is the intermediate state of the above two times
#时间戳时间
import time
print(time.time())

Insert picture description here

#格式化时间
import time
print(time.strftime('%Y-%m-%d'))
print(time.strftime('%Y-%m-%d %H:%M:%S'))

Insert picture description here

#结构化时间
time_obj = time.localtime()
print(time_obj) #显示属性
print(time_obj.tm_day)#类似于对象调用属性的用法

Insert picture description here
Conversion between several time formats:

Insert picture description here
Formatted time string (Format string):

  • % y two-digit year representation (00-99)
  • % Y Four-digit year representation (000-9999)
  • % m month (01-12)
  • Day of the month in% d (0-31)
  • % H 24-hour hour (0-23)
  • % I 12-hour clock hours (01-12)
  • % M minutes (00 = 59)
  • % S seconds (00-59)
  • % a local simplified weekday name
  • % A local full weekday name
  • % b local simplified month name
  • % B local full month name
  • % c local corresponding date and time representation
  • One day in% j (001-366)
  • % p Equivalent of local AM or PM
  • % U Week of the year (00-53) Sunday is the beginning of the week
  • % w week (0-6), Sunday is the start of the week
  • % W Week of the year (00-53) Monday is the beginning of the week
  • % x local corresponding date representation
  • % X local corresponding time representation
  • % Z The name of the current time zone
  • %%% sign itself

random module:

  • import random
  • random.random () # 0-1 random decimal
  • random.uniform (1,10) # 1-10 random decimal
  • random.randint (1,2) #Closed interval, random integer including 2
  • random.randrange (1,2) # [1,2) does not contain 2

Randomly draw a value:

lst = [1,2,3,'aaa',('wahaha','qqxing')]
ret = random.choice(lst)
print(ret)

Insert picture description here
Randomly extract multiple values:

lst = [1,2,3,'aaa',('wahaha','qqxing')]
ret = random.sample(lst,2)
print(ret)

Insert picture description here
Shuffle the order, shuffle the order in the original list, you can only sort the list:

lst = [1,2,3,'aaa',('wahaha','qqxing')]
random.shuffle(lst)
print(lst)

Insert picture description here
Generate a six-digit + letter verification code:

def rand_code(n=6):
	code = ''
	for i in range(n):
		num = str(random.randint(0,9))
		rand_alph = chr(random.randint(97,122))
		rand_alph_upper = chr(random.randint(65,90))
		atom_code = random.choice([num,rand_alph,rand_alph_upper])
		code += atom_code
	return code	
ret = rand_code()		
print(ret)

Insert picture description here

os module:

  • os.makedirs ('dirname1 / dirname2') can generate multiple levels of recursive directories
  • os.removedirs ('dirname1') If the directory is empty, delete it, and recurse to the previous directory, if it is also empty, delete it, and so on
  • os.mkdir ('' dirname ') generates a single-level directory
  • os.listdir ('dirname') List all files and subdirectories in the specified directory, including hidden files, and print them as a list
  • os.remove () deletes a file
  • os.stat ('path / filename') Get file / directory information

  • os.system ('bash command') Run the shell command and display it directly
  • os.popen ('bash command'). read () Run shell command to get the execution result
  • os.getcwd () Get the current working directory, that is, the directory path where the python script works
  • os.chdir ('dirname') Change the current script working directory

  • os.path.abspath (path) returns the absolute path normalized by path
  • os.path.split (path) split path into directory and file name binary return
  • os.path.dirname (name) returns the path directory. It's actually the first element of os.path.split (path)
  • os.path.basename (path) returns the last file name of path, which is the second element of os.path.split (path). If the path ends with / or \, a null value is returned.
  • os.path.exists (path) If path exists, return True, otherwise False
  • os.path.isfile (path) If path is an existing file, return True
  • os.path.isdir (path) returns true if path is an existing directory
  • os.path.getsize (path) returns the size of path

sys module:

  • sys.argv command line parameter list, the first element is the path of the program itself
  • sys.exit (n) exits the program, exit (0) when exiting normally, sys.exit (1) exits by mistake
  • sys.version Get the version information of the python interpreter
  • sys.path returns the search path of the module, using the value of the PYTHONPATH environment variable during initialization
  • sys.platform returns the operating system platform name

Serialization module:

What is serialization? The process of converting the original dictionary, list, etc. into a string is called serialization .

Why serialize:
1. Make custom objects persistent in some form of storage
2. Pass objects from one place to another

Insert picture description here
The json module provides four functions: dupms, dump, loads, load

import json
dic = {'aaa':'bbb','ccc':'ddd'}
str_dic = json.dumps(dic) #转成序列化
print(dic)
print(str_dic,type(str_dic))

ret = json.loads(str_dic) #从序列化转成数据结构字典

Insert picture description here


Restriction of json format: The key in json format must be a string. If the number is a key, then dumps will be forcibly converted. json does not support tuples as keys! ! !

dic = {1:2,3:4}
str_dic = json.dumps(dic)
print(str_dic)
new_dic = json.loads(str_dic)
print(new_dic)

Insert picture description here
Chinese format, need to use ensure_ascii

dic3 = {'abc':(1,2,3),'country':'中国'}
str_dic3 = json.dumps(dic3,ensure_ascii = False)
print(str_dic3)

Insert picture description here
Two modules for serial numbers:

  • json, used to convert between string and python data types
  • Pickle is used to convert between Python-specific types and Python data types.
    -The pickle module provides four functions: dumps, dump, loads, and load can serialize any data type in python

Here to explain, json is a data structure that all languages ​​can recognize.
If we serialize a dictionary or a json file, then java code or js code can also be used.
But if we use pickle for serialization, other languages ​​can't understand what this is ~
So, if your serialized content is a list or dictionary, we highly recommend that you use the json module

hashlib module:

Digest algorithm module

It can convert a variable of string data type into a fixed-length ciphertext string. Each character in this string is a hexadecimal number.
For the same string, no matter how many times the string is the same, no matter what environment and how many times it is executed, in any language, using the same algorithm, the result will always be the same.

md5 algorithm:

import hashlib
s = 'alex3714'
#md5是一个算法,32位的字符串,每个字符都是一个十六进制
md5_obj = hashlib.md5()
md5_obj.update(s.encode('utf-8'))
res = md5_obj.hexdigest()
print(res,len(res),type(res))

Insert picture description here
sha1 algorithm: a 40-bit string, each character is a hexadecimal.

import hashlib
s = 'alex3714'
sha1_obj.update(s.encode('utf-8'))
res_sha = sha1_obj.hexdigest()
print(res_sha,len(res_sha),type(res_sha))

Insert picture description here

logging module:

Features:

  • Specification of log format
  • Simplified operation
  • Hierarchical management of logs

Use of logging module:

  • Common configuration type, simple, can be customized poor
  • Object configuration type, complex, and can be customized

Object configuration type:

  1. Create a logger object
  2. Create a file management operator
  3. Create a screen management operator
  4. Create a log output format
  5. File management operator, bind a format
  6. Screen management operator, bind a format
  7. logger object binding file management operator
  8. logger object binding screen management operator
import logging
#创建一个logger对象
logger = logging.getLogger()
#创建一个文件管理操作符
fh = logging.FileHandler('logger.log',encoding='utf-8')
#创建一个屏幕管理操作符
sh = logging.StreamHandler()
#创建一个日志输出的格式
format1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#文件管理操作符 绑定一个格式
fh.setFormatter(format1)
#屏幕管理操作符 绑定一个格式
sh.setFormatter(format1)
logger.setLevel(logging.DEBUG) #显示debug,info
#logger对象 绑定文件管理操作符
logger.addHandler(fh)

#logger对象绑定屏幕管理操作符
logger.addHandler(sh)

logger.warning('警告信息')
logger.debug('debug message')
logger.info('info message')

Insert picture description here
Insert picture description here
At the same time, the log file of logger.org was generated.

Published 26 original articles · praised 5 · visits 777

Guess you like

Origin blog.csdn.net/weixin_44730235/article/details/105374796