Hi all,

I was writing a script that took file paths as arguments, and stumbled 
upon a phenomenon that I wasn't previously aware of, but which I'm 
guessing is probably quite well known.

There is a difference between the way the current working directory is 
understood by the bash shell and the way it is understood by Python.

Suppose, when I run the script, my shell says I am in:

        /some/path/to/a/directory

Further suppose that, in that path, 'a' is a symbolic link:

        /some/path/to/a -> /some/other/path/to/a

If I give my Python script the following relative path as an argument 
on the command line:

        ../../../that/points/to/a/file

I would expect it to point to

        /some/path/that/points/to/a/file

And, indeed, my shell would make the same assumption and I could use 
tab-completion to fill in the path based on that assumption.


But if my Python script runs that relative path through 
os.path.abspath(), the result is actually:

        /some/other/path/that/points/to/a/file

Which may or may not exist, but is certainly not the path I intended!

This is because Python's understanding of the current working 
directory has all symbolic links followed, so as far as Python is 
concerned, I am not, and can never be, in:

        /some/path/to/a/directory

Because it contains a symbolic link. Instead, I must be in:

        /some/other/path/to/a/directory
        
As far as I can tell, this is by design and not entirely unique to 
Python. (e.g. the program 'optipng' seems to have the same issue).

In Python, it seems as though the way to eliminate the discrepancy 
while maintaining cross-platform compatibility is to add a check to 
see whether the program is running under a shell that sets $PWD (see 
bash(1)), or on a system that has pwd(1), and, if it is, then resolve 
any relative paths relative to $PWD or the output of pwd, rather than 
relative to os.getcwd().

Or, if adding all that platform-specific complexity would double the 
length of your simple script, document it as a limitation and tell 
your users they're holding the script wrong when they run into it.

Patrick

-- 
  Next meeting: Online, Jitsi, Tuesday, 2020-12-01 20:00
  Check to whom you are replying
  Meetings, mailing list, IRC, ...  http://dorset.lug.org.uk
  New thread, don't hijack:  mailto:dorset@mailman.lug.org.uk

Reply via email to