Wednesday, 15 July 2015

system - Expand a relative path but not follow any symlink in the path in Python -


This is a subtle question, I know, but I hope you can bear with me for a moment . There is a symlink for

/ tmp / dir / home / user / some / dir . Let's say your current working directory is / tmp / dir .

Even something like is expanding. is not possible, as instead of / tmp / dir pwd returns / home / user / some / dir Returns command returns relative to ../dir/../dir/subdir , .././././dir/foo , Etc.

So my question: Is there any reliable work that extends the path relative path, but does not follow the symlink which can exist in the relative path. For example, I want to get the / tmp / dir / subdir and not / home ../dir/../dir/subdir In case / user / some / diamonds / subdir .

Just to avoid nothing, the answer is no. os.path.abspath , Os.path.realpath , os. Path.expanduser , or os.path.relpath .

Looks like you care for this weird behavior.

There is nothing about this in the Linux manpage, but it says ...

int chdir (const char * path);

[...]

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

... though with no indication why it resolves the symbolic link.

Therefore, you can not technically make an existing working directory of / tmp / dir , even if you do not claim your shell otherwise.

However, the fact is that the shell's underlying cd command sets the value you entered to the environment variable PWD , so that you do You can ...

  $ cd / tmp / dir $ python & gt; & Gt; & Gt; Import OS & gt; & Gt; & Gt; Os.getcwd () '/ home / user / some / dir' & gt; & Gt; & Gt; Os.environ ['PWD'] '/ tmp / dir' & gt; & Gt; & Gt; Os.path.normpath (os.path.join (os.venviron ['PWD'], '../dir/../dir/subdir')) '/ tmp / dir / subdir'   

... Although this process may fail when the process did not start from the shell.

No comments:

Post a Comment