How to determine the Dropbox folder location programmatically?

前端 未结 8 1156
故里飘歌
故里飘歌 2020-12-06 09:38

I have a script that is intended to be run by multiple users on multiple computers, and they don\'t all have their Dropbox folders in their respective home directories. I\'d

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-06 10:26

    This should work on Win7. The use of getEnvironmentVariable("APPDATA") instead of os.getenv('APPDATA') supports Unicode filepaths -- see question titled Problems with umlauts in python appdata environvent variable.

    import base64
    import ctypes
    import os
    
    def getEnvironmentVariable(name):
        """ read windows native unicode environment variables """
        # (could just use os.environ dict in Python 3)
        name = unicode(name) # make sure string argument is unicode
        n = ctypes.windll.kernel32.GetEnvironmentVariableW(name, None, 0)
        if not n:
            return None
        else:
            buf = ctypes.create_unicode_buffer(u'\0'*n)
            ctypes.windll.kernel32.GetEnvironmentVariableW(name, buf, n)
            return buf.value
    
    def getDropboxRoot():
        # find the path for Dropbox's root watch folder from its sqlite host.db database.
        # Dropbox stores its databases under the currently logged in user's %APPDATA% path.
        # If you have installed multiple instances of dropbox under the same login this only finds the 1st one.
        # Dropbox stores its databases under the currently logged in user's %APPDATA% path.
        # usually "C:\Documents and Settings\\Application Data"
        sConfigFile = os.path.join(getEnvironmentVariable("APPDATA"),
                                   'Dropbox', 'host.db')
    
        # return null string if can't find or work database file.
        if not os.path.exists(sConfigFile):
            return None
    
        # Dropbox Watch Folder Location is base64 encoded as the last line of the host.db file.
        with open(sConfigFile) as dbxfile:
            for sLine in dbxfile:
                pass
    
        # decode last line, path to dropbox watch folder with no trailing slash.
        return base64.b64decode(sLine)
    
    if __name__ == '__main__':
        print getDropboxRoot()
    

提交回复
热议问题