How to determine the Dropbox folder location programmatically?

前端 未结 8 1152
故里飘歌
故里飘歌 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:17

    Note: requires Dropbox >= 2.8

    Dropbox now stores the paths in json format in a file called info.json. It is located in one of the two following locations:

    %APPDATA%\Dropbox\info.json
    %LOCALAPPDATA%\Dropbox\info.json
    

    I can access the %APPDATA% environment variable in Python by os.environ['APPDATA'], however I check both that and os.environ['LOCALAPPDATA']. Then I convert the JSON into a dictionary and read the 'path' value under the appropriate Dropbox (business or personal).

    Calling get_dropbox_location() from the code below will return the filepath of the business Dropbox, while get_dropbox_location('personal') will return the file path of the personal Dropbox.

    import os
    import json
    
    def get_dropbox_location(account_type='business'):
        """
        Returns a string of the filepath of the Dropbox for this user
    
        :param account_type: str, 'business' or 'personal'
        """
        info_path = _get_dropbox_info_path()
        info_dict = _get_dictionary_from_path_to_json(info_path)
        return _get_dropbox_path_from_dictionary(info_dict, account_type)
    
    def _get_dropbox_info_path():
        """
        Returns filepath of Dropbox file info.json
        """
        path = _create_dropox_info_path('APPDATA')
        if path:
            return path
        return _create_dropox_info_path('LOCALAPPDATA')
    
    def _create_dropox_info_path(appdata_str):
        r"""
        Looks up the environment variable given by appdata_str and combines with \Dropbox\info.json
    
        Then checks if the info.json exists at that path, and if so returns the filepath, otherwise
        returns False
        """
        path = os.path.join(os.environ[appdata_str], r'Dropbox\info.json')
        if os.path.exists(path):
            return path
        return False
    
    def _get_dictionary_from_path_to_json(info_path):
        """
        Loads a json file and returns as a dictionary
        """
        with open(info_path, 'r') as f:
            text = f.read()
    
        return json.loads(text)
    
    def _get_dropbox_path_from_dictionary(info_dict, account_type):
        """
        Returns the 'path' value under the account_type dictionary within the main dictionary
        """
        return info_dict[account_type]['path']
    

    This is a pure Python solution, unlike the other solution using info.json.

提交回复
热议问题