2026年4月8日 研究日志¶
今天在做明天出门的材料准备,还参加了研究生展示会议,主要项目的进度一点都没有推进(摊手)。不过前两天都已经把要参会的摘要写完发给老师了,摸两天鱼也没事吧(笑)。总之今天给大家放点存货,总结一下Python中文本输出的几种办法。
给与使用者信息的几种办法:¶
In [ ]:
print("Processing completed.")
print(f"Result: {value}")
In [ ]:
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Task started")
logging.warning("Low disk space")
logging.error("Failed to load configuration")
In [ ]:
import warnings
warnings.warn("This function will be removed in future versions.", DeprecationWarning)
In [ ]:
if n < 0:
raise ValueError("n must be non-negative")
In [ ]:
import sys
sys.stderr.write("Warning: configuration file not found\n")
In [ ]:
from rich import print
print("[bold green]Task completed successfully![/bold green]")
In [ ]:
name = "Alice"
msg = f"Hello, {name}. Welcome!"
示例(Template):¶
In [ ]:
from string import Template
t = Template("Hello, $name!")
print(t.substitute(name="Alice"))
| 需求 | 推荐方式 |
|---|---|
| 简单输出 | print() |
| 需要日志等级、可配置性 | logging |
| 提醒用户但不中断程序 | warnings |
| 输入非法、必须终止 | raise |
| 错误输出但不中断 | sys.stderr.write() |
| 美观 CLI、彩色输出 | rich / colorama |
| 构建复杂文本模板 | f-string / Template |