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

Albert-Jan Roskam sjeik_appie at hotmail.com
Wed Jan 10 07:59:32 EST 2018


From: eryk sun <eryksun at gmail.com>
Sent: Wednesday, January 10, 2018 3:56 AM
To: tutor at python.org
Cc: Albert-Jan Roskam
Subject: Re: [Tutor] Why does os.path.realpath('test_main.py') give different results for unittest than for testing statement in interpreter?
  

On Tue, Jan 9, 2018 at 2:48 PM, Albert-Jan Roskam
<sjeik_appie at hotmail.com> wrote:
>
>> I think that it would be a great enhancement if os.realpath would return the UNC path if
>> given a mapped drive in Windows, if needed as extended path (prefixed with "\\?\UNC\").
>> That's something I use all the time, unlike symlinks, in Windows.
>
>pathlib can do this for you, or call os.path._getfinalpathname. 

I tried: 
>>> from os.path import _getfullpathname
>>> _getfullpathname(r"H:")
'h:\\path\\to\\folder'
>>> import os
>>> os.getcwd()
'h:\\path\\to\\folder'

I expected h:\ to be \\server\share\foo. The fact that the current working directory was returned was even more unexpected.

>>I recently helped someone that wanted the reverse, to map the resolved
>>UNC path back to a logical drive:

Oh dear. Why would anybody *want* the drive letters? They are only useful because (a) they save on keystrokes (b) they bypass the annoying limitation of the cd command on windows, ie. it does not work with UNC paths. Driveletter-->UNC conversion is useful when e.g. logging file paths. I do wonder whether the method used to assign the drive letter matters with the . I know net use, pushd, subst. I use 'net use' for more or less permanent drives and pushd/popd to get a temporary drive, available letter (cd nuisance).

>We can't assume in general that a user's special folders (e.g.
>Desktop, Documents) are in the default location relative to the
>profile directory. Almost all of them are relocatable. There are shell
>APIs to look up the current locations, such as SHGetKnownFolderPath.
>This can be called with ctypes [1]. For users other than the current
>user, it requires logging on and impersonating the user, which
>requires administrator access.
>
>[1]: https://stackoverflow.com/a/33181421/205580

Interesting code! I have used the following, which uses SHGetFolderPath, ie. without 'Known'.
from win32com.shell import shell, shellcon
desktop = shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, 0, 0)

Working with ctypes.wintypes is quite complex!




More information about the Tutor mailing list