[英]Curious behavior in sys.path when changing volumes in Windows CMD
I have just noticed some curious behavior of sys.path
and Windows CMD and would like to know what is happening and why. 我刚刚注意到sys.path
和Windows CMD的一些奇怪的行为,并想知道发生了什么以及为什么。
In the following two examples, I print out sys.path
, change volume to D:
, cd
into a directory, change volume back to C:
and finally print out sys.path
again. 在以下两个示例中,我打印出sys.path
,将卷更改为D:
sys.path
将cd
更改为目录,将卷更改回C:
最后再次打印出sys.path
。 I do this with two very similar PYTHONPATH
s. 我用两个非常相似的PYTHONPATH
来做这件事。
With PYTHONPATH=D:\\
: 使用PYTHONPATH=D:\\
:
C:\Users\z003w3we>python -c "import sys; print(sys.path)"
['', 'D:\\', <others>]
C:\Users\z003w3we>D:
D:\>cd UserData
D:\UserData>C:
C:\Users\z003w3we>python -c "import sys; print(sys.path)"
['', 'D:\\', <others>]
Everything is as expected. 一切都如预期。
With PYTHONPATH=D:
(notice the missing trailing \\
): 使用PYTHONPATH=D:
注意缺少尾随\\
):
C:\Users\z003w3we>python -c "import sys; print(sys.path)"
['', 'D:\\', <others>]
C:\Users\z003w3we>D:
D:\>cd UserData
D:\UserData>C:
C:\Users\z003w3we>python -c "import sys; print(sys.path)"
['', 'D:\\UserData', <others>]
C:\Users\z003w3we>echo %PYTHONPATH%
D:
Now, instead of D:
, we suddenly have D:\\UserData
in sys.path
. 现在,我们突然在sys.path
拥有D:\\UserData
而不是D:
. Notice that PYTHONPATH
is unchanged. 请注意, PYTHONPATH
没有变化。
I could not reproduce the same behavior with PowerShell; 我无法使用PowerShell重现相同的行为; both PYTHONPATH
s exhibit the first behavior. PYTHONPATH
表现出了第一种行为。
As I said, I would be very interested in learning what is going on here. 正如我所说,我会非常有兴趣了解这里发生的事情。
CMD sets a conventionally hidden environment variable named "=D:" for the working directory on drive D:. CMD为驱动器D:上的工作目录设置一个名为“= D:”的常规隐藏环境变量。 The Python process inherits this environment variable, and the Windows API uses it when GetFullPathNameW
is called to resolve the drive-relative path "D:" as a fully-qualified path. Python进程继承此环境变量,并且在调用GetFullPathNameW
时,Windows API使用它来将驱动器相对路径“D:”解析为完全限定路径。
In CMD we can list all environment variables including the 'hidden' ones via set "". 在CMD中,我们可以通过set“”列出所有环境变量,包括“隐藏”变量。 This command depends on a bug, but one that's existed for so long that it's now a feature. 这个命令取决于一个bug,但是它存在了很长时间以至于它现在是一个特性。 To list just the hidden ones, use set "" | findstr /r "^="
要仅列出隐藏的,请使用set "" | findstr /r "^="
set "" | findstr /r "^="
. set "" | findstr /r "^="
。 For example: 例如:
C:\>set "" | findstr /r "^="
=C:=C:\
C:\>cd /d E:\UserData
E:\UserData>c:
C:\>set "" | findstr /r "^="
=C:=C:\
=E:=E:\UserData
C:\>set PYTHONPATH=E:
C:\>python -c "import sys; print(sys.path[1]); sys.exit(0xFF)"
E:\UserData
C:\>set "" | findstr /r "^="
=C:=C:\
=E:=E:\UserData
=ExitCode=000000FF
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.