os.normpath为什么不将前导双斜杠折叠起来? [英] Why doesn't os.normpath collapse a leading double slash?
问题描述
在Unix下, os.path.normpath 将多个斜杠折叠成单个斜杠,除非在路径的开头出现了两个斜杠.为什么例外?
Under Unix, os.path.normpath collapses multiple slashes into single ones except when exactly two slashes appear that the start of the path. Why the exception?
为了说明,我得到以下转换:
To illustrate, I get the following transformations:
//double/slash/stays -> //double/slash/stays
/double/slash//gone// -> /double/slash/gone/
double//slash//gone/ -> double/slash/gone
///triple/slash/gone -> /triple/slash/gone
////quad/slash/gone -> /quad/slash/gone
这对我来说似乎很奇怪.我可以模糊地想象这对于SMB挂载或URL是有用的,但我认为我并不在乎那些. Python的行为是否有任何隐藏的智慧,还是我应该自己折叠领导者//
This seems strange to me. I can vaguely imagine this is useful for SMB mounts or URLS, but I don't think I care about those. Is there any hidden wisdom to Python's behaviour, or should I just collapse the leading // myself?
[更新] 鉴于以下答案,看来最好的办法不是不要折叠//,而是要么接受//,要么将其视为错误.
[update] In view of the answer below, it looks like the best thing is not to collapse the //, but to either just accept it, or to treat it as an error.
推荐答案
因为POSIX允许以实现定义的方式处理以两个斜杠开头的路径.换句话说,//foo在所有POSIX系统上不一定与/foo相同.
Because POSIX allows treating a path beginning with two slashes in an implementation-defined manner. In other words, //foo does not necessarily mean the same thing as /foo on all POSIX systems.
来自 IEEE标准1003.1 :
以两个连续的斜杠开头的路径名可能会被解释 以实现定义的方式,尽管有两个以上的领导 斜杠应视为单个斜杠.
A pathname that begins with two successive slashes may be interpreted in an implementation-defined manner, although more than two leading slashes shall be treated as a single slash.
另请参见此错误报告(由于无效而被关闭).
See also this bug report (which was closed as invalid).
这篇关于os.normpath为什么不将前导双斜杠折叠起来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!