Python os.path.isdir 对于点返回 true

标签 python windows shell os.path

我正在用 python 编写自己的 shell。现在我正在尝试在我的 shell 中执行 cd 命令。

执行此命令的函数有几个变量:

self.current_dir = "C:\\" - 默认值,它的变化取决于用户使用 cd 命令的输入

dir = "..." - 用户键入的请求目录。 “...”是导致问题的输入示例。

这是我的代码:

def command_cd(self, dir):
    if os.path.isdir(self.shell.current_dir + dir):
        self.shell.current_dir = self.shell.current_dir + dir + "\\"

问题是,由于某种奇怪的原因,当用户输入点时,os.path.isdir(self.shell.current_dir + dir)返回True(就像我上面给出的变量的示例输入)。

即使您更改点数(甚至超过 5 个点),也会出现问题,而且我真的不知道是什么原因导致的。

显然没有名为 ... 或类似名称的文件夹。

如果我的问题不够清楚,请发表评论,我会进行编辑

最佳答案

. 是当前目录,.. 是父目录,并且没有任何大于两个点的引用。

但是,os.path.isdir() 返回 True 的原因是因为 python 将所有大于两个点的内容注册为一个点。

import os

print(os.path.abspath(".......") == os.path.abspath("."))
print(os.path.abspath("....") == os.path.abspath("."))

# and that
print(os.path.samefile('......', '.'))
# also prints True

它们都会打印 True,因为 ............ 指向同一个地方.


正如 chepner 在评论中指出的那样,这个问题在 POSIX 系统中不会发生,而是由 os.stat 错误地等同于 '....''.' (事实并非如此,请参阅稍后的编辑)


重要编辑:

埃里克森评论:

Windows os.path.isdir is implemented by calling GetFileAttributes, which calls NtQueryAttributesFile. Like all file system functions, first it has to convert the DOS path to a native NT path. To the kernel "." and ".." are just normal names, so the runtime library first has to normalize the path via the function RtlGetFullPathName_Ustr, which also gets used by os.path.abspath, so the result is similar. The way it reduces more than two dots and trailing spaces in the final component is a legacy inherited from DOS. It's doing its best to emulate an OS from the 1980s.

因此这个问题与python本身无关,因为这个问题也出现在Windows cmd中,cd c:\.....cd .\... .\.. Windows 仍然会让你通过用一个点引用两个或两个以上的点来逃脱惩罚。因为它是从 DOS 继承的,可将两个以上的点减少为一个并删除尾随空格。

关于Python os.path.isdir 对于点返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46608731/

相关文章:

python - 是否有更多的 pythonic,可能是一个衬里,来迭代列表中的字符串?

windows - 使用 GCC-4.9.1_x64 编译 Clang 时命令语法不正确

windows - 创建可以处理多个文件拖放的批处理文件

bash - 遍历文件并删除某些行

python - Tensorflow CUDA - CUPTI 错误 : CUPTI could not be loaded or symbol could not be found

python - Numpy:分配目的地是只读的 - 广播

windows - 使用批处理备份注册表

Python 将所有其他内容压缩到同一文件中

azure - 如何使用 Azure DevOps 专门安排管道

python - 找到 N 个矩形重叠的有效方法