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!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


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

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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