How to handle OSX Aliases in Python with os.walk()?

帅比萌擦擦* 提交于 2019-12-10 20:35:24

问题


I'm traversing a directory tree using Python 2.7.x, getting the file and directory sizes as it traverses. The problem I'm running into is that it is mistaking alias files for directories, and then throwing an error that there's "No Such File or Directory".

Code below:

def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return total_size

for dirName, subdirList, fileList in os.walk(rootDir, topdown=False):

    dirSize = get_size(dirName) #this throws an error on alias files

    for fname in fileList:
              #do other things

I tried os.path.isdir() as well and that doesn't work. Further, I tried

return File.FSResolveAliasFile(path, True)[0].as_pathname()

But that doesn't seem to pick up all the alias files.

Any thoughts?


回答1:


See my comment on https://stackoverflow.com/a/21197881/838253 for background.

The short answer is that you can't do this in Python. There was a library which resolved alias, but this relied on an obsolete Carbon library, and no longer works.

You can detect alias at the terminal.

It may be possible to distinguish because alias have extended attributes.




回答2:


It seems there are three type of link in MacOSX.

  • Alias (This can be executed from right click menu "create alias")
  • Soft link
  • Hard link

Alias link seems to be specific on MacOSX.

And python 2.7 seems not to recognize Alias link as link.

To make sure, try this.

os.path.islink("./alias-you-created")
>>> False

So it is not treated as link.

IMO I think python 2.7 is not support MacOSX Alias as link. But I can't understand why MacOSX has such function, it's too complicated.

Here is related information I found.

  • What is Alias?
    • What Are Aliases, Symbolic Links, and Hard Links in Mac OS X?
    • How to Create and Use Symlinks on a Mac
    • + or @ mark after running 'ls -al'
  • Python link related question
    • Is os.walk() missing symlinks to directories?
    • how to find target path of link if the file is a link file


来源:https://stackoverflow.com/questions/22262791/how-to-handle-osx-aliases-in-python-with-os-walk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!