在Python中,展开相对路径,但不要跟随路径中的任何符号链接

2024-04-26 21:29:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这是个微妙的问题,但我希望你能容忍我一会儿。在

假设/tmp/dir/home/user/some/dir的符号链接。还假设您当前的工作目录是/tmp/dir。在

甚至扩展.似乎也不可能,因为os.getcwd()返回{},而不是{},这是{}命令返回的。相对目录也可以是../dir/../dir/subdir.././././dir/foo,等等

所以我的问题是:有没有可靠的函数可以对相对路径进行路径扩展,但不遵循可能存在于相对路径中的符号链接。以../dir/../dir/subdir为例,我希望得到/tmp/dir/subdir,而不是{}。在

为了避免得到我不想要的东西,答案不是os.path.abspathos.path.realpathos.path.expanduser,或者{}。在


Tags: path函数命令目录homefooos链接
2条回答

不知道你在找什么,但是。。。您可以编写一个函数,从相对路径和当前工作目录生成“逻辑”完整路径,然后检查生成的路径是否确实存在于系统中。该函数可能看起来像:

import os

def absolute_path(path):
    wd = os.getcwd()
    full = os.path.join(wd, path)

    parts = full.split(os.sep)
    kept = []
    skip = 0
    for part in reversed(parts):
        if part == '..':
            skip += 1
        elif skip == 0:
            kept.insert(0, part)
        else:
            skip -= 1
    return os.sep + os.path.join(*kept)

似乎you're not the first注意到了^{}的这种奇怪行为。在

Linux手册页中没有关于它的内容,但是a similar page说。。。在

int chdir(const char *path);

[...]

The chdir() function makes the directory named by path the new current directory. If the last component of path is a symbolic link, chdir() resolves the contents of the symbolic link. If the chdir() function fails, the current directory is unchanged.

…尽管没有解释为什么它会解析符号链接。在

因此,从技术上讲,您不能拥有当前的工作目录/tmp/dir,即使您的shell另有声明。在

但是,您可以利用shell内置的cd命令将环境变量PWD设置为您输入的值,因此您可以这样做。。。在

$ cd /tmp/dir
$ python
>>> import os
>>> os.getcwd()
'/home/user/some/dir'
>>> os.environ['PWD']
'/tmp/dir'
>>> os.path.normpath(os.path.join(os.environ['PWD'], '../dir/../dir/subdir'))
'/tmp/dir/subdir'

…尽管在进程不是从shell启动的情况下,它可能会失败。在

相关问题 更多 >