Source code for mango.utils

import os
import sys
import subprocess
import time
import logging
import uuid

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


def get_uid():
    """
    Get a UUID.
    
    Returns
    -------
    uid : str
        A UUID.
    """
    return uuid.uuid4()


[docs]def filter_dict(dct, *keys): """ Filter a dictionary, including only the named keys. Parameters ---------- dct : :class:`dict` A dictionary. keys : any number of :class:`str` These keys are extracted from `d`. Returns ------- filtered_d : :class:`dict` A copy of `d`, but containing only the keys from `keys`. """ return {k: v for k, v in dct.items() if k in keys}
def ensure_dir_exists(path): """ Ensure that the directory tree to the path exists. Parameters ---------- path : str the path to a file or directory (that may not exist yet) """ split_path = os.path.splitext(path) if split_path[0] != path: # path is to a file make_path = os.path.dirname(split_path[0]) else: # path is to a dir make_path = split_path[0] os.makedirs(make_path, exist_ok = True) logger.debug('Ensured dir {} exists'.format(make_path))
[docs]def run_mongodb(mongo_bin_path = None, dbpath = None, **kwargs): """ Start a MongoDB server using the data at `dbpath`, looking for the mongod executable in the dir `mongo_bin_path`. If mongod is visible on your system path, pass an empty string ('') to `mongo_bin_path`. If `dbpath` is None, mango will attempt to find your MongoDB install based on the default location for your OS. Parameters ---------- mongo_bin_path : :class:`str` dbpath : :class:`str` kwargs Keyword arguments are passed to the :class:`subprocess.Popen` constructor. Returns ------- process : :class:`subprocess.Popen` The subprocess that the MongoDB server is running in. """ if dbpath is None: dbpath = os.path.join(os.getcwd(), 'mongodb') if sys.platform.startswith('win'): # windows if mongo_bin_path is None: mongo_bin_path = r'C:\Program Files\MongoDB\Server\3.4\bin' mongo_cmd = 'mongod.exe' # TODO: linux support commands = [os.path.join(mongo_bin_path, mongo_cmd), '--dbpath', dbpath] proc = subprocess.Popen(commands, **kwargs) return proc