我怎么知道一个文件是一个给定目录的后代? [英] How can I tell if a file is a descendant of a given directory?
问题描述
但符号链接整个事情陷入混乱。沿着被检查的文件或目录的路径的任何目录都可以是符号链接,任何符号链接都可以有任意的符号链接链接到其他符号链接。在这一点上我的大脑融化,我不知道该怎么做。我试过编写代码来处理这些特殊情况,但是它很快就变得复杂了,我认为我做错了。有没有一个相当优雅的方式来做到这一点?
我使用Python,所以任何提到这样做的图书馆将是很酷的。否则,这是一个非常不依赖语言的问题。 使用 os.path.realpath
和 os.path.commonprefix
:
os.path.commonprefix(['/ the / dir /',os。 path.realpath(filename)])==/ the / dir /
os.path.realpath
将展开文件名中的任何符号链接以及 ..
。 os.path.commonprefix
有点变幻莫测 - 它并不真正测试路径,只是简单的字符串前缀,所以你应该确保你的目录结尾在一个目录分隔符。如果你不这样做,它会声明 / the / dirtwo / filename
也在 / the / dir
p>
On the surface, this is pretty simple, and I could implement it myself easily. Just successively call dirname() to go up each level in the file's path and check each one to see if it's the directory we're checking for.
But symlinks throw the whole thing into chaos. Any directory along the path of either the file or directory being checked could be a symlink, and any symlink could have an arbitrary chain of symlinks to other symlinks. At this point my brain melts and I'm not sure what to do. I've tried writing the code to handle these special cases, but it soon gets too complicated and I assume I'm doing it wrong. Is there a reasonably elegant way to do this?
I'm using Python, so any mention of a library that does this would be cool. Otherwise, this is a pretty language-neutral problem.
Use os.path.realpath
and os.path.commonprefix
:
os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == "/the/dir/"
os.path.realpath
will expand any symlinks as well as ..
in the filename. os.path.commonprefix
is a bit fickle -- it doesn't really test for paths, just plain string prefixes, so you should make sure your directory ends in a directory separator. If you don't, it will claim /the/dirtwo/filename
is also in /the/dir
这篇关于我怎么知道一个文件是一个给定目录的后代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!