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

eryk sun eryksun at gmail.com
Tue Jan 9 22:56:16 EST 2018


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
recently helped someone that wanted the reverse, to map the resolved
UNC path back to a logical drive:

https://bugs.python.org/issue32442

> And I would also welcome a convenience function in the os.path module that does
> expanduser, expandvars, normpath, realpath, and maybe more.

pathlib implements expanduser, but it's still lame on Windows for a
user other than the current user. It assumes all user profiles are in
the same directory instead of directly getting the user's profile
path. Anyway, expanduser is of limited use.

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

You can log a user on without a password by calling LsaLogonUser to
request an MSV1 S4U (service for user) logon. The access token will
only be identification level, unless the script is running as a SYSTEM
service. But identification level is enough to query the location of a
user's known folders. I don't recommended calling LsaLogonUser via
ctypes if you have the option to write an extension module in C/C++,
but I did manage to get it working with ctypes [2]. For example:

    >>> from security_lsa import logon_msv1_s4u
    >>> from knownfolders import FOLDERID, get_known_folder_path

    >>> logon_info = logon_msv1_s4u('Administrator')
    >>> get_known_folder_path(FOLDERID.Desktop, logon_info.Token)
    'C:\\Users\\Administrator\\Desktop'

[2]: https://stackoverflow.com/a/43233332/205580

Also, please don't use expanduser to enable applications to spam the
profile directory with configuration files and directories. Use the
local and roaming application data directories.


More information about the Tutor mailing list