SoFunction
Updated on 2024-11-12

Examples of common usage of python modules in detail

1. time module (※※※※)

import time # Import time module

print(()) # Returns a timestamp of the current time, which can be used to calculate program runtime
print(()) # Returns a structured time format in local time, with parameters defaulting to timestamps
print() # Returns a structured time format in UTC time
print((())) # Convert structured time to timestamps
print(("%Y-%m-%d %X",())) # Convert structured time to string time
print(("2019:9:30:12:55:36","%Y:%m:%d:%X")) # Convert string time to structured time
print(()) # Convert a structured time or tuple representing a time to the format 'Sun Jun 20 23:21:05 1993'
print(()) #Converting timestamps to formats,Defaults to the parameter

PS: Due to the usual habits, strftime is more commonly used, strptime and it is the reverse operation, the following method of output format can be more in line with people's habits

import datetime # Import the datetime module
print(()) #exports2019-09-30 15:15:09.562809formats 

2. Random module (※※)

import random

print(()) # Returns a random floating point number between 0 and 1
print((1,3)) # Returns a random integer between 1 and 3, including 3
print((1,3)) # Returns a random integer between 1 and 3, excluding 3
print(([1,'23',[4,5]])) # Returns a random piece of data from a list
print(([1,'23',[4,5]],2)) # Randomly return two pieces of data in a list
print((1,3)) # Returns a floating point number between 1 and 3
item=[1,3,5,7,9]
(item)
print(item) #particle marking the following noun as a direct objectitemhit-and-miss list

3. os module (※※※※)

import os

() # Returns the path to the current script working directory
("dirname") # Change the current script working directory
('dirname1/dirname2') # Generate multi-level recursive catalogs
('dirname1') # If the directory is empty it is deleted and recursed to the previous directory, if it is also empty it continues to be deleted, and so on.
('dirname') # Generate single-level catalogs
('dirname') # Delete single level empty directory, if the directory is not empty it cannot be deleted and reports an error
('dirname') #Returns a list of all files and subdirectories in the specified directory, including hidden files.
() # Delete a file
("oldname","newname") # Rename a file or directory
('path/filename') # Get the file or directory
 # Output the line terminator used by the current platform ("\r\n" for Win, "\n" for Linux).
 # Output the string used to split the path of the file (under Win it's ;, under Linux it's :).
(path) # Returns the absolute path of the path normalization
(path) # Returns a path-separated binary of directories and filenames.
(path) # Returns the directory of the path
(path) # Returns the filename of path, or null if path ends in / or \.
(path) True if #path exists, False if it doesn't.
(path) Returns True if #path is an absolute path.
(path) Returns True if #path is an existing file, False otherwise.
(path) Returns True if #path is an existing directory, False otherwise.
(path1[, path2[, ...]]) # Combine multiple paths and return them, parameters before the first absolute path are ignored.
(path) # Returns the last access time of the file or directory pointed to by path.
(path) #come (or go) backpathThe last modification time of the file or directory you are pointing to

PS: One of the more commonly used.

4. sys module (※※※)

import sys

 # Command line parameter List, the first element is the path to the program itself
(n) # Exit the program, exit(0) on normal exit.
 # Get the version information of the Python interpreter program
 # Maximum Int value
 # Returns the search path of the module, initialized with the value of the PYTHONPATH environment variable.
 #Returns the operating system platform name

PS: one of the more commonly used, the following code to achieve the progress of the print bar, the use of flush to refresh the screen printing

import sys,time

for i in range(100):
 ('#')
 (1)
 ()

5、json&pickle(※※※※)

import json
dic={'name':'alvin','age':23,'sex':'male'} #Define a dictionary for the dictionary format
f=open('Serialized objects','w')
j=(dic) # Serialize the dictionary, i.e., single quotes into double quotes, and then add single or double quotes at the top into a string format available in all programming languages
(j) # can also be used with dump usage, these two lines are then equivalent to (dic,f)
()
f=open('Serialized objects')
data=(()) #Deserialize a string,i.e. turning a string format into a dictionary format,It is also possible to useloadusage,These two lines are then equivalent todata=(f)

PS: dump and load usage is more concise, but limited to file operations, so we still recommend dumps and loads. in addition, dumps and loads are not necessarily used in conjunction, as long as the string meets the format of the dumps, you can directly loads operation, dump and load the same reason. pickle and json usage is basically the same! json can be used to exchange data between different languages, while pickle can only be used between python. json can only serialize the most basic data types, while pickle can serialize all data types, including classes, functions can be serialized (not common)

6. shelve module (※※※)

import shelve

def member_info(name, age):
 print("Member info:", name, age)

name = ['Jack', 'Maxwell', 'Tom']
info = {'name': 'Maxwell', 'age': 18}

with ('demo') as data:
 data['name'] = name #Persistent lists
 data['info'] = info #Persistent Dictionary
 data['func'] = member_info

PS: the shelve module is simpler than the pickle module, there is only one open function, which returns a dictionary-like object that can be read and written. the key must be a string, and the value can be a data type supported by Python.

7. xml module (※※)

xml format, using <> to distinguish data structures:

<?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>

Module for manipulating xml in python:

import  as ET
 
tree = ("")
root = ()
print()
#---------- traversing xml documents ----------
for child in root:
 print(, )
 for i in child:
  print(,)
#---------- only traverses year nodes ----------
for node in ('year'):
 print(,)
#---------- modify ----------
for node in ('year'):
 new_year = int() + 1
  = str(new_year)
 ("updated","yes")
("")
#---------- delete node ----------
for country in ('country'):
 rank = int(('rank').text)
 if rank > 50:
  (country)
('')


How to create xml documents:

import  as ET

new_xml = ("namelist")
name = (new_xml,"name",attrib={"enrolled":"yes"})
age = (name,"age",attrib={"checked":"no"})
sex = (name,"sex")
 = '33'
name2 = (new_xml,"name",attrib={"enrolled":"no"})
age = (name2,"age")
 = '19'
et = (new_xml) # Generate document objects
("", encoding="utf-8",xml_declaration=True)
(new_xml) #Print the generated format

PS: json is simpler to use than xml, but xml appeared very early, so much so that now many system interfaces are still xml

8. re module (※※※※※)

import re
 
ret=('a..in','helloalvin') #The metacharacter . Usage of the metacharacter . indicates that there is a character
print(ret) # Output ['alvin'], is to retrieve all the substrings in the string that satisfy the format and put them in the list
ret=('^a...n','alvinhelloawwwn') Usage of the # metacharacter ^ to indicate matching from the beginning of the string
print(ret) #output['alvin']
ret=('a...n$','alvinhelloawwwn') # Usage of the metacharacter $ to match from the end of the string
print(ret) #output['awwwn']
ret=('abc*','abcccc') #The use of the metacharacter * means that the character c is repeated many times, or 0 times, and will automatically match the most times, called greedy matching.
print(ret) # Output ['abcccc']
ret=('abc+','abccc') The usage of the # metacharacter +, which indicates that the character c is repeated multiple times, with a minimum of 1, will automatically match the maximum number of times
print(ret) #['abccc']
ret=('abc?','abccc') # The metacharacter ? is used to indicate that the character c repeated 0 or 1 times will automatically match 1 time
print(ret) # Output ['abc']
ret=('abc{1,4}','abccc') # Usage of the metacharacter {} to indicate that the character c is repeated the specified number of times in the range, which will automatically match the maximum number of times
print(ret) #exports['abccc']

PS: The above metacharacters *,+,? ,{}, etc. are greedy matches, i.e., match as many times as possible. sign can be turned into an inert match

ret=('abc*?','abcccccc') # Inert match character c is the least number of times 0 times
print(ret) # Output ['ab']

ret=('a[bc]d','acd') Usage of the character set [] for # metacharacters, indicating that one of the character sets is selected for matching
print(ret) # Output ['acd']
ret=('[a-z]','acd') # Character set [] has functional symbols:-^\, a-z for all letters from a to z.
print(ret) # Output ['a', 'c', 'd']
ret=('[.*+]','+') #Symbols other than -^\ become normal characters and are not functional.
print(ret) #Output ['.' , '+']
ret=('[^ab]','45bdha3') #^ means "not" in the character set [], and ^ab is the non-characters a and b.
print(ret) # Output ['4', '5', 'd', 'h', '3']
ret=('[\d]','45bdha3') #\d i.e. matching characters in numeric format
print(ret) # Output ['4', '5', '3']
import re
ret=('c\l','abc\le') #The use of metacharacter \ can convert general characters and special characters to each other, here \l has a special meaning, so the string can not be retrieved
print(ret) # Output []
ret=('I\b','I am LIST') #\b means match a special character, such as a space, &, #, etc.
         #\d means match any decimal number, equivalent to class [0-9].
         #\D means match any non-numeric character, equivalent to class [^0-9]
         #\s means match any blank character, equivalent to class [ \t\n\r\f\v]
         #\S means match any non-white space character, equivalent to class [^\t\n\r\f\v]
         #\w means match any alphanumeric character, equivalent to the class [a-zA-Z0-9_]
         # \W means match any non-alphanumeric character, equivalent to class [^a-zA-Z0-9_]
print(ret) # Output []
ret=(r'I\b','I am LIST') #\b has a special meaning, so it needs to be escaped again \\b or r'\b'
print(ret) # Output ['I']
ret=('c\\l','abc\le')
print(ret) # Output []
ret=('c\\\\l','abc\le') There is a difference between #python interpreter escaping and re escaping, so you need to pass in more than one \ for escaping
print(ret) #Output ['c\\l']
ret=(r'c\\l','abc\le') # can also be escaped again by prefixing it with r directly
print(ret) #Output ['c\\l']
m = (r'(ad)+', 'add') # Usage of metacharacter () to match what's in () as a whole
m = (r'(ad)+', 'adadad') # Look at ab as a whole
print(m) # Output ['ad'] preferentially due to preferential matching within the group ()
m1 = (r'(?:ad)+', 'adadad') # To deprioritize the above, add ? :
print(m1) # Output ['ad','ad','ad']
ret=('(ab)|\d','rabhdg8sd')
print(()) # Output ab, function in the string to find the first match to the first sub-string returns an object, you can get the sub-string through the group () method, if there is no match then return None
ret=('(?P<id>\d{2})/(?P<name>\w{3})','23/com') # Fixed format ?P<group name>, id and name indicate the group name, not involved in the match
print(()) #Output23/com
print(('id')) #exports23,group(Subgroup name)You can get the corresponding value,Grouping is meant to be reusable many times,increase efficiency

Common methods of the re module (already covered above and)

import re

('a','abc').group() # and usage is the same, but can only match from the beginning of the string
ret=('[ab]','abcd') #Split by 'a' first, you get '' on the left and 'bcd' on the right, then split 'bcd' by b, you get '' on the left and 'cd' on the right
print(ret) # Output ['', '', 'cd']
ret=('\d','abc','alvin5yuan6',1) #Parameter 1 indicates the matching rule or character, parameter 2 indicates the replaced string, parameter 3 indicates the matched string, parameter 4 indicates the number of matches, if not filled in, the default is to replace all the characters.
print(ret) # Output alvinabcyuan6
ret=('\d','abc','alvin5yuan6') # can get the replaced string and the number of times it was replaced
print(ret) #output('alvinabcyuanabc', 2)
obj=('\d{3}') # First give the rule to an object
ret=('abc123eeee') # Objects calling module methods
print(()) # Output 123, the advantage is that it can be called repeatedly, avoiding the repetition of writing rules and improving efficiency
ret=('\d','ds3sy4784a') # Generate an iterator from the lookups
print(ret) # Returns an iterator
print(next(ret).group()) # Output '3', you can use group to iterate the output result
print(next(ret).group()) #exports'4',This iterative approach is commonly used for larger data sets,memory-neutral

9. Logging module (※※※※※)

import logging 

('debug message') #Log Level Level CRITICAL>ERROR>WARNING>INFO>DEBUG>NOTSET
('info message') 
('warning message') 
('error message') 
('critical message') # Output WARNING:root:warning message
          #ERROR:root:error message
          #CRITICAL:root:critical message
          # The default level of the log is WARNING, printing itself and later, in the format Log Level: Logger Name: User Output Message


import logging 
(level=, 
     format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', 
     datefmt='%a, %d %b %Y %H:%M:%S', 
     filename='/tmp/', 
     filemode='w') # Use basicConfig to set the format, level to set the logging level; format to specify the display format; datefmt to specify the date and time format;
filenameSpecify the filename for log storage;filemodeindicate clearly and with certaintyfilenameThe way the file is opened,The default value is“a”
 
('debug message') 
('info message') 
('warning message') 
('error message') 
('critical message')# output cat /tmp/
         #Sun, 13 Oct 2019 16:29:53 test_logging.py[line:9] DEBUG debug message
         #Sun, 13 Oct 2019 16:29:53 test_logging.py[line:10] INFO info message
         #Sun, 13 Oct 2019 16:29:53 test_logging.py[line:11] WARNING warning message
         #Sun, 13 Oct 2019 16:29:53 test_logging.py[line:12] ERROR error message
         #Sun, 13 Oct 2019 16:29:53 test_logging.py[line:13] CRITICAL critical message

PS: The format formatting parameter above may be used:

%(name)s: the name of the Logger
  %(levelno)s: log level in numeric form
  %(levelname)s: log level in text form
 %(pathname)s: the full pathname of the module from which the log output function was called, may not be available
  %(filename)s: filename of the module that calls the log output function
  %(module)s: the name of the module that calls the log output function
  %(funcName)s: the name of the function that calls the log output function
 %(lineno)d: the line of code where the statement calling the log output function is located
  %(created)f: the current time expressed as a floating point number in the UNIX standard for expressing time.
  %(relativeCreated)d: outputs the number of milliseconds since the Logger was created.
  %(asctime)s: current time in string form, default format "2019-10-13 16:49:45,896" (milliseconds after comma)
  %(thread)d: thread ID, may not be available
 %(threadName)s: thread name, may not be available
  %(process)d: process ID, may not be available
  %(message)s: messages output by the user

About the logger object

import logging

logger = () #The getLogger([name]) function returns a logger object, or root logger if no name is present.
fh = ('') # Create a handler to write to the log file
ch = () # Create another handler for output to the console
formatter = ('%(asctime)s - %(name)s - %(levelname)s - %(message)s') #Formatter specifies the log display format
(formatter)
(formatter)
(fh)
(ch) The #logger object can add multiple fh and ch objects

('logger debug message')
('logger info message')
('logger warning message')
('logger error message')
('logger critical message') # Output 2019-10-14 19:51:23,552 - root - WARNING - logger warning message
    #2019-10-14 19:51:23,552 - root - ERROR - logger error message
    #2019-10-14 19:51:23,552 - root - CRITICAL - logger critical message

PS: Here you can use () for the logger to set the log level, the default log level for WARNIING, in addition, if you create two logger objects, if the parameter name is the same, the return of the Logger instance is the same, after the log level of a logger to cover the front of the log level, and the back of the log will be in front of the log to print it again!

10. configparser module (※※※※)

Many software documents are formatted this way:

View Code
So how do you generate a document like this in python:

import configparser
 
config = ()
config["DEFAULT"] = {'ServerAliveInterval': '45',
      'Compression': 'yes',
      'CompressionLevel': '9'} # Add data via config, similar to a dictionary
config[''] = {}
config['']['User'] = 'hg'
config[''] = {}
topsecret = config['']
topsecret['Host Port'] = '50022'
topsecret['ForwardX11'] = 'no'
config['DEFAULT']['ForwardX11'] = 'yes'
with open('', 'w') as configfile:
 (configfile)

Operation:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[]
User = hg
 
[]
Port = 50022
ForwardX11 = no

11. hashlib module (※※)

import hashlib

m=hashlib.md5() # You can also use m=hashlib.sha256(), this module mainly provides SHA1,SHA224,SHA256,SHA384,SHA512, MD5 algorithm
('hello'.encode('utf8')) # The string "hello" to be hashed.
print(()) # Output 5d41402abc4b2a76b9719d911017c592
('alvin'.encode('utf8'))
print(()) #output92a7e713c30abbb0319fa07da2a5c4af
m2=hashlib.md5() # Define another variable
('helloalvin'.encode('utf8')) # Process the first two strings concatenated
print(()) #exports92a7e713c30abbb0319fa07da2a5c4af,uppermIt's hash first.hello,add onalvinhash (computing)

So now there is a very large database that counts a lot of commonly used strings, and so it may be reverse solved, called bumping. To avoid this you can use this method below:

import hashlib

m = hashlib.sha256('898oaFs09f'.encode('utf8')) # Add a hashed random string before processing
('alvin'.encode('utf8'))
print(())#output 04d0625659c27032274faf030cd842676be3b8912bb255f9d3445d86c1e5de80


Of course python also has an hmac module, which internally encrypts the key and content we create and then process it:

import hmac

h = ('alvin'.encode('utf8'))
('hello'.encode('utf8'))
print (()) #output320df9832eab4c038b6c1d7ed73a5940

summarize

The above is a small introduction to the python module commonly used examples of detailed, I hope to help you, if you have any questions please leave me a message, I will reply to you in a timely manner. Here also thank you very much for your support of my website!
If you find this article helpful, please feel free to reprint it, and please note the source, thank you!