Python: Common Module 2, python Module

Source: Internet
Author: User

Python: Common Module 2, python Module
1. hashlib module --- Digest algorithm

Import hashlib md5 = hashlib. md5 () md5.update ('How to use md5 in python hashlib? ') Print md5.hexdigest () Calculation Result: d26a53750bc40b38b65a520292f69306
Use MD5 for encryption

If the data volume is large, you can call update () multiple times in multiple parts. The calculation result is the same:

md5 = hashlib.md5()md5.update('how to use md5 in ')md5.update('python hashlib?')print md5.hexdigest()

MD5 is the most common Digest algorithm, which is very fast. The generated result is a fixed 128-bit byte, which is usually represented by a 32-bit hexadecimal string. Another common Digest algorithm is SHA1. Calling SHA1 is similar to calling MD5:

import hashlib sha1 = hashlib.sha1()sha1.update('how to use sha1 in ')sha1.update('python hashlib?')print sha1.hexdigest()

The result of SHA1 is 160 bits, usually expressed in a 40-bit hexadecimal string. SHA256 and SHA512 are more secure than SHA1, but the more secure the algorithm is, the longer the digest length.

2. configparser Module

This module is applicable to the configuration file in a format similar to the windows INI file. It can contain one or more sections, and each section can have multiple parameters (Key = value ).

Create a file

The Common Document formats of a lot of software are as follows:

[DEFAULT]ServerAliveInterval = 45Compression = yesCompressionLevel = 9ForwardX11 = yes  [bitbucket.org]User = hg  [topsecret.server.com]Port = 50022ForwardX11 = no

How can I use python to generate such a document?

import configparserconfig =configparser.ConfigParser()config["DEFAULT"] = {'ServerAliveInterval': '45',                      'Compression': 'yes',                     'CompressionLevel': '9',                     'ForwardX11':'yes'                     }config['bitbucket.org'] = {'User':'hg'}config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}with open('example.ini', 'w') as configfile:   config.write(configfile)
Search for files
Import configparserconfig = configparser. configParser () # --------------------------- search for file content, print (config. sections () # [] config. read ('example. ini ') print (config. sections () # ['bitbucket. org ', 'topsecret .server.com'] print ('bytebong. com 'in config) # Falseprint ('bitbucket. org 'in config) # Trueprint (config ['bitbucket. org '] ["user"]) # huplint (config ['default'] ['compression']) # yesprint (config ['topsecret .server.com'] ['forwardx11']) # noprint (config ['bitbucket. org ']) # <Section: bitbucket.org> for key in config ['bitbucket. org ']: # note that the default key print (key) print (config. options ('bitbucket. org ') # Find 'bitbucket' in the same for loop. print (config. items ('bitbucket. org ') # Find 'bitbucket. print (config. get ('bitbucket. org ', 'compression') # yes value corresponding to the key in the get method Section
Add, delete, modify, and delete operations
import configparserconfig = configparser.ConfigParser()config.read('example.ini')config.add_section('yuan')config.remove_section('bitbucket.org')config.remove_option('topsecret.server.com',"forwardx11")config.set('topsecret.server.com','k1','11111')config.set('yuan','k2','22222')config.write(open('new2.ini', "w"))
Simple function configuration of the logging Module
import logging  logging.debug('debug message')  logging.info('info message')  logging.warning('warning message')  logging.error('error message')  logging.critical('critical message') 

By default, the logging module of Python prints logs to the standard output and only displays logs greater than or equal to the WARNING level, this indicates that the default log level is set to WARNING (log level CRITICAL> ERROR> WARNING> INFO> DEBUG). The default log format is Log Level: Logger name: User Output Message.

Flexibly configure the log level, log format, and output location:

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='/tmp/test.log',                      filemode='w')    logging.debug('debug message')  logging.info('info message')  logging.warning('warning message')  logging.error('error message')  logging.critical('critical message')

Configuration parameters:

Logging. the basicConfig () function can use specific parameters to change the default behavior of the logging module. The available parameters include: filename: Create FiledHandler with the specified file name, so that logs are stored in the specified file. Filemode: Specifies the file opening mode. This parameter is used when filename is specified. The default value is "a" or "w ". Format: Specify the log display format used by handler. Datefmt: Specifies the date and time format. Level: Set the Log level stream of rootlogger (which will be explained later): Use the specified stream to create StreamHandler. You can specify the output to sys. stderr, sys. stdout, or file (f = open ('test. log', 'w'). The default value is sys. stderr. If both filename and stream parameters are listed, the stream parameters are ignored. Possible format strings used in the format parameter: % (name) s Logger name % (levelno) s log level % (levelname) s text form: Log Level % (pathname) s the complete path name of the module that calls the log output function, may not have % (filename) s the file name of the module that calls the log output function % (module) module name % (funcName) s for calling log output function % (lineno) d for calling log output function code line % (created) f current time, expressed in UNIX standard as the number of floating points of time % (relativeCreated) d when the log information is output, the number of milliseconds since Logger creation % (asctime) the current time in the string format of s. The default format is "16:49:45, 896 ". The comma is followed by the millisecond % (thread) d thread ID. There may be no % (threadName) s thread name. % (Process) d process ID may not exist. There may be no messages output by % (message) s users
View Codelogger object Configuration
Import logginglogger = logging. getLogger () # create a handler for writing log files. fileHandler ('test. log', encoding = 'utf-8') # create another handler for output to the console ch = logging. streamHandler () formatter = logging. formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') fh. setLevel (logging. DEBUG) fh. setFormatter (formatter) ch. setFormatter (formatter) logger. addHandler (fh) # You can add multiple logger and ch objects to the logger object. addHandler (ch) logger. debug ('logger debug message') logger.info ('logger info message') logger. warning ('logger warning message') logger. error ('logger error message') logger. critical ('logger critical message ')

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.