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

推荐订阅源

N
News and Events Feed by Topic
D
DataBreaches.Net
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Recorded Future
Recorded Future
Y
Y Combinator Blog
C
Check Point Blog
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
小众软件
小众软件
F
Full Disclosure
S
SegmentFault 最新的问题
Blog — PlanetScale
Blog — PlanetScale
B
Blog RSS Feed
Martin Fowler
Martin Fowler
P
Proofpoint News Feed
博客园 - 司徒正美
量子位
The GitHub Blog
The GitHub Blog
T
The Blog of Author Tim Ferriss
T
Tenable Blog
P
Privacy International News Feed
T
The Exploit Database - CXSecurity.com
C
Cyber Attacks, Cyber Crime and Cyber Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
G
Google Developers Blog
P
Proofpoint News Feed
T
Threatpost
Know Your Adversary
Know Your Adversary
aimingoo的专栏
aimingoo的专栏
Latest news
Latest news
Security Latest
Security Latest
Cyberwarzone
Cyberwarzone
A
About on SuperTechFans
P
Palo Alto Networks Blog
Stack Overflow Blog
Stack Overflow Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Hacker News
The Hacker News
A
Arctic Wolf
AWS News Blog
AWS News Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
NISL@THU
NISL@THU
Last Week in AI
Last Week in AI
Hacker News - Newest:
Hacker News - Newest: "LLM"
Spread Privacy
Spread Privacy
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Application and Cybersecurity Blog
Application and Cybersecurity Blog
I
InfoQ
J
Java Code Geeks
H
Help Net Security

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