[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

error in os.chdir

On Sun, Jul 1, 2018 at 1:44 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Sat, 30 Jun 2018 23:36:40 +0000, eryk sun wrote:
>> Only use forward slashes for legacy DOS paths passed to Windows API
>> functions. Do not use forward slashes for paths in command line
>> arguments, \\?\ prefixed paths, or registry paths.
> I don't see why this is relevant, or at least not the "command line
> arguments" and "registry paths" parts.

Command-line arguments are relevant to executing a child process, e.g.
via subprocess.Popen.

> I guess that if the user is using a path beginning with \\?\ they may or
> may not need to use backslashes, but I have no way of testing it, and I
> would expect that Python will correctly replace //?/ with backslashes the
> same as it does for any other file system path.

The Windows API handles this, but not for a path that begins with
\\?\. The intent of this prefix is to bypass DOS-path normalization --
allowing paths with length up to 32K characters that can use otherwise
reserved DOS-device names or names ending in spaces or dots.

> (Besides, Python doesn't have an API for interacting directly with the
> registry.)

The standard library has winreg -- or _winreg in 2.x.

Bear in mind that forward slash is just a  name character in NT. If a
coder assumes that Windows automatically replaces forward slash with
backslash for registry paths, it could lead to a mistake such as the

    >>> hkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER, 'test')
    >>> subkeya = winreg.CreateKey(hkey, 'test_a1/test_a2/test_a3')
    >>> subkeyb = winreg.CreateKey(hkey, 'test_b1\\test_b2\\test_b3')
    >>> winreg.EnumKey(hkey, 0)
    >>> winreg.EnumKey(hkey, 1)

In the test_a case, instead of a tree of keys
"test_a1\test_a2\test_a3", we get a single key named
"test_a1/test_a2/test_a3". The test_b case creates the intended tree.

I grant that having to explicitly say that forward slash isn't
supported in registry paths is certainly beyond what's required, as is
having to state that forward slash isn't supported in the native API
(e.g. NtCreateFile, NtOpenFile). We only need to clearly state that
the Windows API allows using forward slash as the path separator in
file paths that do not begin with the \\?\ prefix. I prefer to also
add a warning about command-line arguments, since it isn't an
improbable or inconsequential problem, and it's so easy to state
upfront rather than letting someone waste hours unravelling a cryptic
failure, given the path separator isn't something one is likely to
consider as the source of the problem.