Fab von Bellingshausen Fab von Bellingshausen - 1 year ago 80
Python Question

Python subprocess pwd inconsistent when file structure includes alias

When I run the following script

#!/usr/bin/env python
import subprocess

the result is

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

whilst from my Ubuntu terminal, the command




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

Answer Source

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
>>> os.path.realpath(path)

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'))

However, the best option is to use os.getcwd() from the Python standard library:

>>> os.getcwd()

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download