Introduction to python packages and logging
Python package and logging log
1. Package
Package: A package with an __init__.py file in a folder is used to manage multiple modules.
The structure of the package is as follows:
bake ├── __init__.py ├── api ├── __init__.py ├── policy.py └── versions.py ├── cmd ├── __init__.py └── manage.py └── db ├── __init__.py └── models.py
Create a test.py at the same level as bake Import policy.py:
import bake.api.policy bake.api.policy.get() #导入的名字太长了,可以起别名 import bake.api.policy as p p.get() #from 导入在__init__.py修改 from . import policy #我们需要在policy文件中向sys.path添加了当前的路径 import os import sys sys.path.insert(os.path.dirname(__file__)) #print(__file__)查看一下 #使用__all__,在__init__.py中 __all__ = ["policy"] #或 from . import policy
Summary:
import package.package.package
from package.package.package import module
Path:
Absolute: import from the outer layer
Relative: import from the current (.) or from the parent (..)
When using relative paths, they must be at the end of the package Outer layer and same level
from package import *
Need to do the operation in __init__.py
python2: The import folder (without __init__.py) will report an error
python3: The import folder (without __init__.py) will not report an error
Related recommendations: "Python Video Tutorial"
二, logging module
The logging module is used to record various statuses of the software, transaction records, error records, login records...
1. Functional simple configuration:
import logging logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
By default, python's logging module prints logs to the standard output, and only displays logs greater than or equal to WARNING level, which proves that the default level is WARNING
Log level: CRITICAL > ERROR > WARNING > INFO > DEBUG
2. Flexible configuration of log level, log mode, input location (low configuration version)
Only Write logs and cannot output to the public screen
import logging logging.basicConfig(level = logging.DEBUG, format = '%(astime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s', datefmt = '%Y-%m-%d %H:%M:%S', filename = 'test.log', filemode = 'a') dic = {"key":123} logging.debug(dic) num = 100 logging.info(f"用户余额:{num - 50}") try: num = int(input("请输入数字:")) except Exception as e: logging.warning("e") logging.error('error message') logging.critical('critical message')
The default behavior of the logging module can be changed through specific parameters in the basicConfig() function. The available parameters are:
filename: Use Creates a FiledHandler for the specified file name so that the log will be stored in the specified file.
filemode: File opening mode, this parameter is used when filename is specified. The default value is "a" and can also be specified as "w".
format: Specify the log display format used by the handler.
datefmt: Specify date and time format.
level: Set the logging level
stream: Create a StreamHandler with the specified stream. You can specify the output to
sys.stderr, sys.stdout or file (f=open(‘test.log’,’w’)), the default is sys.stderr. If both filename and stream parameters are listed, the stream parameter will be ignored.
Format strings that may be used in the format parameter:
%(name)s Logger’s name
%(levelno)s numeric form The log level of
%(levelname)s The log level in text form
%(pathname)s The full pathname 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)s The module name that calls the log output function
%(funcName)s The function name that calls the log output function
%(lineno)d The line of code where the statement that calls the log output function is located
%(created)f The current time, expressed as a UNIX standard floating point number representing time
%(relativeCreated)d The number of milliseconds since the Logger was created when outputting log information.
%(asctime)s The current time in the form of a string. The default format is "2003-07-08 16:49:45,896". What follows the comma is the thread ID in milliseconds
%(thread)d. There may be no
%(threadName)s thread names. There may be no
%(process)d process ID. There may not be messages output by
%(message)s users
3.logger object configuration (medium version)
import logging logger = logging.getLogger() # 创建一个logger fh = logging.FileHandler('test.log',mode="a",encoding='utf-8') # 文件 ch = logging.StreamHandler() # 屏幕 formatter = logging.Formatter('%(asctime)s - %(name)s - %(filename)s - [line:%(lineno)d] - %(levelname)s - %(message)s') # 将屏幕和文件都是用以上格式 logger.setLevel(logging.DEBUG) # 设置记录级别 fh.setFormatter(formatter) # 使用自定义的格式化内容 ch.setFormatter(formatter) logger.addHandler(fh) #logger对象可以添加多个fh和ch对象 logger.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')
The above is the detailed content of Introduction to python packages and logging. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.
