how to get os.py to use an ./ntpath.py instead of Lib/ntpath.py

ruck john.ruckstuhl at gmail.com
Tue Sep 11 15:13:45 EDT 2012


On Tuesday, September 11, 2012 12:21:24 AM UTC-7, Tim Golden wrote:
> And so it does, but you'll notice from the MSDN docs that the \\?
> syntax must be supplied as a Unicode string, which os.listdir
> will do if you pass it a Python unicode object and not otherwise:

I was saying os.listdir doesn't like the r'\\?\' prefix.
But Tim corrects me -- so yes, Steven's earler suggestion "Why don't you just prepend a '?' to paths like they tell you to?" does work, when I supply it in unicode.
Good:
    >>> os.listdir(u'\\\\?\\C:\\Users\\john\\Desktop\\sandbox\\goo')
   [u'voo...']
Bad:
    >>> os.listdir('\\\\?\\C:\\Users\\john\\Desktop\\sandbox\\goo')

    Traceback (most recent call last):
      File "<pyshell#3>", line 1, in <module>
        os.listdir('\\\\?\\C:\\Users\\john\\Desktop\\sandbox\\goo')
    WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: '\\\\?\\C:\\Users\\john\\Desktop\\sandbox\\goo/*.*'

Thanks to both of you for taking the time to teach.

BTW, when I posted the original, I was trying to supply my own customized ntpath module, and I was really puzzled as to why it wasn't getting picked up! According to sys.path I expected my custom ntpath.py to be chosen, instead of the standard Lib/ntpath.py.

Now I guess I understand why.  I moved Lib/ntpath.* out of the way, and learned that during initialization, Python is importing "site" module, which is importing "os" which is importing "ntpath" -- before my dir is added to sys.path.  So later when I import os, it and ntpath have already been imported, so Python doesn't attempt a fresh import.

To get my custom ntpath.py honored, need to RELOAD, like:
  import os
  import ntpath
  reload(ntpath)
  print 'os.walk(\'goo\') with isdir override in custom ntpath'
  for root, dirs, files in os.walk('goo'):
      print root, dirs, files

where the diff betw standard ntpath.py and my ntpath.py are:
  14c14,19
  < from genericpath import *
  ---
  > from genericpath import *
  >
  > def isdir(s):
  >     return genericpath.isdir('\\\\?\\' + abspath(s + '\\'))
  > def isfile(s):
  >     return genericpath.isfile('\\\\?\\' + abspath(s + '\\'))

I'm not sure how I could have known that ntpath was already imported, since *I* didn't import it, but that was the key to my confusion.

Thanks again for the help.
John



More information about the Python-list mailing list