[Tutor] Why does os.path.realpath('test_main.py') give different results for unittest than for testing statement in interpreter?

Steven D'Aprano steve at pearwood.info
Mon Jan 8 01:47:00 EST 2018


On Mon, Jan 08, 2018 at 12:39:07AM +0000, Alan Gauld via Tutor wrote:

> To be fair realpath() does do a tiny bit of magic in that it
> checks if the file (or any part of the path) is a link (aka
> shortcut) and tries to give you the actual path to the
> original file - ie it follows the link.

As I actually explained in my previous email, the one which has 
disappeared into the aether, realpath resolves symbolic links and 
replaces them by the real path they represent.

But that's only on Unix/Linux/Mac, on Windows it does not.

Symbolic links, however, are *not* Windows shortcuts. Windows shortcuts 
are just a special sort of file, one which the Windows file explorer 
treats as an alias to another file or folder.

Symbolic links on Unix are a feature of the file system itself, not a 
kind of file.

What's the difference?

With a shortcut, if you tell Python or some other program to open a 
shortcut, it will treat it as an ordinary file (because that's what it 
is!) and read from the shortcut file itself. Only programs like Windows 
Explorer which have been specially programmed to follow shortcuts will 
do so.

But with a symbolic link, programs don't need to know anything about 
them. If you have a link:

/A/link ---> /B/C/file

then *any* program will treat opening /A/link as if it were /B/C/file.

In other words:

- under Windows, a shortcut is a regular file, unless the programmer
  takes special action to treat it as an alias;

- under Unix, a symbolic link is an alias, unless the programmer 
  takes special action to treat it as a symbolic link.


(Aside: starting with Windows Vista, NTFS also supports symbolic links, 
like Unix. But few Windows users know this, or use them.)




-- 
Steve


More information about the Tutor mailing list