惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
云风的 BLOG
云风的 BLOG
博客园 - 聂微东
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
P
Proofpoint News Feed
GbyAI
GbyAI
WordPress大学
WordPress大学
NISL@THU
NISL@THU
V
Vulnerabilities – Threatpost
T
The Exploit Database - CXSecurity.com
D
DataBreaches.Net
F
Full Disclosure
Recent Commits to openclaw:main
Recent Commits to openclaw:main
V
Visual Studio Blog
Last Week in AI
Last Week in AI
L
LangChain Blog
AWS News Blog
AWS News Blog
Martin Fowler
Martin Fowler
V
V2EX
The Hacker News
The Hacker News
Scott Helme
Scott Helme
T
Troy Hunt's Blog
G
GRAHAM CLULEY
L
Lohrmann on Cybersecurity
Cloudbric
Cloudbric
C
Cyber Attacks, Cyber Crime and Cyber Security
O
OpenAI News
月光博客
月光博客
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
B
Blog RSS Feed
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
G
Google Developers Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
IT之家
IT之家
C
Cisco Blogs
Google DeepMind News
Google DeepMind News
T
Tenable Blog
Jina AI
Jina AI
T
Tor Project blog
The Cloudflare Blog
Y
Y Combinator Blog
Spread Privacy
Spread Privacy
L
LINUX DO - 热门话题
Cyberwarzone
Cyberwarzone
Microsoft Security Blog
Microsoft Security Blog
Stack Overflow Blog
Stack Overflow Blog
A
Arctic Wolf

Origin

Agent 安全:环境变量泄露 人生第一次离职,感觉应该写点什么 在 Python 中复现 Race Condition 再看看 SQL 中的 null 迁移 Zeabur 集群 2025Q3 订阅 Recap 再见 xlog 浏览器从 A 到 Z 2024Q3 订阅 Recap 使用 TypeScript 撰写 OmniFocus 脚本 [备忘] Go init 行为 [随笔] 一开始就公布定价 [随笔] Server Action [随笔] Swift 异步:Task vs DispatchQueue [随笔] RSS 与稍后阅读 在 Shell 脚本中嵌入二进制文件 谈谈时区 利用 Fly.io 部署 Windmill 强制关闭 xLog 的 Dark Mode 解决 CentOS8 中 yum 源失效 [随笔] 避免完美主义导致的看似时间不够
Python 的 pth 文件:在程序启动前自动执行命令
Singee · 2025-07-18 · via Origin

Python 的 pth 文件提供了在任何 Python 解释器执行前执行命令的能力,可以方便的执行一些初始化脚本

Python 解释器在启动时会自动 import site 模块(除非启动时指定 -S flag),而 site 模块有一个行为就是会寻找 site-packages 目录(最常用的场景就是我们安装包的目录)下的所有 .pth 文件并依次「执行」它。

需要注意的是, pth 实质上并不是脚本,它的定义是「path configuration file」,格式是每行一个「additional items (one per line) to be added to sys.path」,实际上,它每一行可以是下面的值之一:

  • 空行、注释行(以 # 开头):跳过
  • import 开头的字符串:会被 exec() 解释执行
  • 其他字符串:会被追加进 sys.path 之中

因此,利用第二个能力,我们实质上可以任意执行我们需要的脚本!

🗒️ 注:如果脚本执行出现异常,只会打印出错误而不会阻止解释器的继续执行

可用性 & 执行时机

在 Python 3 的所有版本可用

相关 pth 文件会在 python 解释器启动时执行 —— 这包括执行脚本前、启动解释器前、执行任何用 python 写的程序前(如 pip)

当存在多个 pth 文件时,将采用字母序的方式依次执行 —— 一个值得强调的点是,python 的 virtualenv 就是通过 _virtualenv.pth 执行的 —— 这意味着,我们应当注意 pth 的命名以让其确保在 venv 之前或之后运行