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

推荐订阅源

P
Proofpoint News Feed
博客园 - 聂微东
博客园 - 叶小钗
量子位
Google DeepMind News
Google DeepMind News
Cyberwarzone
Cyberwarzone
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
P
Privacy & Cybersecurity Law Blog
Apple Machine Learning Research
Apple Machine Learning Research
月光博客
月光博客
雷峰网
雷峰网
C
Cybersecurity and Infrastructure Security Agency CISA
Schneier on Security
Schneier on Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
美团技术团队
T
Tenable Blog
T
Threatpost
S
Security Affairs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
The Last Watchdog
The Last Watchdog
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
A
Arctic Wolf
Attack and Defense Labs
Attack and Defense Labs
AWS News Blog
AWS News Blog
AI
AI
W
WeLiveSecurity
H
Help Net Security
G
Google Developers Blog
PCI Perspectives
PCI Perspectives
博客园_首页
S
Securelist
B
Blog RSS Feed
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Forbes - Security
Forbes - Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
Lohrmann on Cybersecurity
云风的 BLOG
云风的 BLOG
Martin Fowler
Martin Fowler
C
CERT Recently Published Vulnerability Notes
H
Hacker News: Front Page
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Spread Privacy
Spread Privacy
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
T
Threat Research - Cisco Blogs
博客园 - 司徒正美
Google Online Security Blog
Google Online Security Blog
T
The Blog of Author Tim Ferriss

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 之前或之后运行