我正在用 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 callingGetFileAttributes
, which callsNtQueryAttributesFile
. Like all file system functions, first it has to convert theDOS
path to a nativeNT
path. To the kernel"."
and".."
are just normal names, so the runtime library first has to normalize the path via the functionRtlGetFullPathName_Ustr
, which also gets used byos.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 fromDOS
. It's doing its best to emulate anOS
from the 1980s.
因此这个问题与python本身无关,因为这个问题也出现在Windows cmd中,cd c:\.....
或cd .\... .\..
Windows 仍然会让你通过用一个点引用两个或两个以上的点来逃脱惩罚。因为它是从 DOS
继承的,可将两个以上的点减少为一个并删除尾随空格。
关于Python os.path.isdir 对于点返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46608731/