Using Python sys, argparse, and logging Modules
This article demonstrates how to use Python's sys module to access interpreter information, argparse for parsing command‑line arguments, and logging for flexible log handling, providing clear code examples for each feature.
sys module
The sys module provides many variables and functions related to the Python interpreter, allowing you to retrieve and set system parameters.
Print Python version
import sys
print("Python version:", sys.version)Get command line arguments
import sys
# 获取命令行参数
args = sys.argv
print("Command line arguments:", args)Print script name
import sys
# 获取脚本名称
script_name = sys.argv[0]
print("Script name:", script_name)Terminate program with sys.exit()
import sys
# 检查是否有足够的命令行参数
if len(sys.argv) < 2:
print("Usage: python script.py")
sys.exit(1)
# 打印文件名
print("Filename:", sys.argv[1])argparse module
The argparse module offers a way to parse command‑line arguments and options, simplifying handling of user input.
Parse command‑line arguments
import argparse
# 创建ArgumentParser对象
parser = argparse.ArgumentParser(description='Process some integers.')
# 添加命令行参数
parser.add_argument("integers", metavar='N', type=int, nargs='+', help='an integer for the accumulator')
# 解析命令行参数
args = parser.parse_args()
# 打印解析后的参数
print("Parsed integers:", args.integers)Add optional argument
import argparse
# 创建ArgumentParser对象
parser = argparse.ArgumentParser(description='Print the square of a number.')
# 添加可选参数
parser.add_argument("--square", dest="num", action="store", type=int, help="display a square of a given number")
# 解析命令行参数
args = parser.parse_args()
# 打印结果
if args.num is not None:
print("Square of", args.num, "is", args.num ** 2)Add sub‑commands
import argparse
# 创建ArgumentParser对象
parser = argparse.ArgumentParser(description='A simple command-line utility.')
subparsers = parser.add_subparsers(dest='command')
# 添加子命令
add_parser = subparsers.add_parser('add', help='Add two numbers')
add_parser.add_argument('a', type=int, help='First number')
add_parser.add_argument('b', type=int, help='Second number')
# 解析命令行参数
args = parser.parse_args()
# 执行子命令
if args.command == 'add':
print(args.a + args.b)logging module
The logging module provides a flexible logging system to record program information, useful for debugging and maintenance.
Create a simple logger
import logging
# 创建一个logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler('example.log')
fh.setLevel(logging.DEBUG)
# 创建一个formatter,用于设定日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
# 给logger添加handler
logger.addHandler(fh)
# 记录一条日志
logger.info('This is an info message.')Print logs to console
import logging
# 创建一个logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# 创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# 创建一个formatter,用于设定日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
# 给logger添加handler
logger.addHandler(ch)
# 记录一条日志
logger.info('This is an info message printed to console.')Set different log levels
import logging
# 创建一个logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler('example.log')
fh.setLevel(logging.DEBUG)
# 创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# 创建一个formatter,用于设定日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# 给logger添加handler
logger.addHandler(fh)
logger.addHandler(ch)
# 记录不同级别的日志
logger.debug('This is a debug message.')
logger.info('This is an info message.')
logger.warning('This is a warning message.')
logger.error('This is an error message.')
logger.critical('This is a critical message.')Summary
The examples above show how to use the sys, argparse, and logging modules to handle program input/output, parse command‑line arguments, and record logs, helping you understand their operation and apply them in real applications.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.