When I run the following script
TL;DR - Use
You could use
os.path.realpath to turn a path containing symlinks into the physical path, resolving any symlinks:
~/src/stackoverflow $ mkdir targetdir ~/src/stackoverflow $ ln -s targetdir symlink ~/src/stackoverflow $ cd symlink ~/src/stackoverflow/symlink $ ~/src/stackoverflow/symlink $ python >>> import os >>> import subprocess >>> import shlex >>> >>> path = subprocess.check_output('pwd').strip() >>> path '/Users/lukasgraf/src/stackoverflow/symlink' >>> os.path.realpath(path) '/Users/lukasgraf/src/stackoverflow/targetdir'
There is also the
-P option to the
pwd command that enforces this.
pwd man page (on OS X):
The pwd utility writes the absolute pathname of the current working directory to the standard output.
Some shells may provide a builtin pwd command which is similar or identical to this utility. Consult the builtin(1) manual page.
The options are as follows: -L Display the logical current working directory. -P Display the physical current working directory (all symbolic links resolved). If no options are specified, the -L option is assumed.
So this would work too:
>>> subprocess.check_output(shlex.split('pwd -P')) '/Users/lukasgraf/src/stackoverflow/targetdir\n' >>>
However, the best option is to use
os.getcwd() from the Python standard library:
>>> os.getcwd() '/Users/lukasgraf/src/stackoverflow/targetdir'
It's not explicitly documented, but it seems to already resolve symlinks for you. In any case, you will want to avoid shelling out (using
subprocess) for something that the standard library already provides for you, like getting the current working directory.