python / python/cpython

On Windows Powershell, venv folders are unexpectedly importable due to how namespace package and venv works

未关闭
#94,957 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib topic-venv type-bug
主要语言
Python
星标
77.2k
派生
36k
平均合并
1 天 9 小时
30 天内合并 PR
558

描述

Bug report

PEP420 introduced implicit namespace package, basically by creating a folder without __init__.py, it is treated as namespace package.

For some reasons, in Windows Powershell, venv added the environment's root folder into sys.path (this behavior was not observed in Linux's venv), e.g.

PS C:\Users\TestUser> python -m venv testenv
PS C:\Users\TestUser> . .\testenv\Scripts\activate
(testenv) PS C:\Users\TestUser> python
Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
[
    [snip] 
    'C:\\Users\\TestUser\\testenv', 
    'C:\\Users\\TestUser\\testenv\\lib\\site-packages'
]

And because of the way namespace package works, you can import some folders that really aren't intended to be importable:

>>> import Include
>>> Include.__path__
_NamespacePath(['C:\\Users\\TestUser\\testenv\\Include'])
>>>

This was a namespace package created from the Include folder in the root of the testvenv folder:

PS C:\Users\TestUser> ls .\testenv\


    Directory: C:\Users\TestUser\testenv


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         7/18/2022   1:15 PM                Include
d-----         7/18/2022   1:15 PM                Lib
d-----         7/18/2022   1:15 PM                Scripts
-a----         7/18/2022   1:15 PM            127 pyvenv.cfg

Similarly, you could have imported Lib and Scripts.

Your environment

Python 3.10.5 (tags/v3.10.5:f377153, Jun 6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先重现报告中的 Windows PowerShell 命令,并在创建和激活 venv 后检查 sys.path。比较 Windows 和 Linux 上 venv 的行为,然后确定 Include、Lib 和 Scripts 目录是如何变得可导入的。当不再能够导入非预期的 venv 目录,同时又不破坏正常的环境导入时,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
powershell, python
领域
operating-systems, tooling
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。