Fab von Bellingshausen
Fab von Bellingshausen

Reputation: 1407

Python subprocess pwd inconsistent when file structure includes alias

When I run the following script

#!/usr/bin/env python
import subprocess
print(subprocess.check_output(["pwd"]))

the result is

/scratch1/name/Dropbox (NAM)/docs/research/Y2/results/s8

whilst from my Ubuntu terminal, the command

pwd

yields

/quake/home/name/docs/research/Y2/results/s8

which is an alias to the first path. Why are they inconsistent?

Upvotes: 0

Views: 1368

Answers (1)

Lukas Graf
Lukas Graf

Reputation: 32640

TL;DR - Use os.getcwd()


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.

From the 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.

Upvotes: 1

Related Questions