Python os.path.expanduser() Examples

The following are 30 code examples for showing how to use os.path.expanduser(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os.path , or try the search function .

Example 1
Project: insightconnect-plugins   Author: rapid7   File:    License: MIT License 7 votes vote down vote up
def connect_key(self, params={}):
        home_dir = (path.expanduser('~'))
        key_file = "{}/.ssh".format(home_dir)
        f = params.get('key').get('privateKey')
        fb = f.get('content')
        fb64 = base64.b64decode(fb)
        fb64 = fb64.decode("utf-8")
        if not path.exists(key_file):
            os.chmod(key_file, 0o700)
        key_file_path = path.join(key_file, "id_rsa")
        with open(key_file_path, 'w+') as f:
        os.chmod(key_file_path, 0o600)"Establishing connection")
        device = {'device_type': params.get('device_type'), 'ip': params.get('host'),
                  'username': params.get('credentials').get('username'), 'use_keys': True, 'key_file': key_file_path,
                  'password': params.get('credentials').get('password'), 'port': params.get('port'),
                  'secret': params.get('secret').get('secretKey'), 'allow_agent': True, 'global_delay_factor': 4}
        self.device_connect = ConnectHandler(**device)
        return self.device_connect 
Example 2
Project: pgcli   Author: dbcli   File:    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def execute_from_file(self, pattern, **_):
        if not pattern:
            message = "\\i: missing required argument"
            return [(None, None, None, message, "", False, True)]
            with open(os.path.expanduser(pattern), encoding="utf-8") as f:
                query =
        except IOError as e:
            return [(None, None, None, str(e), "", False, True)]

        if self.destructive_warning and confirm_destructive_query(query) is False:
            message = "Wise choice. Command execution stopped."
            return [(None, None, None, message)]

        on_error_resume = self.on_error == "RESUME"
            query, self.pgspecial, on_error_resume=on_error_resume
Example 3
Project: pgcli   Author: dbcli   File:    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def write_to_file(self, pattern, **_):
        if not pattern:
            self.output_file = None
            message = "File output disabled"
            return [(None, None, None, message, "", True, True)]
        filename = os.path.abspath(os.path.expanduser(pattern))
        if not os.path.isfile(filename):
                open(filename, "w").close()
            except IOError as e:
                self.output_file = None
                message = str(e) + "\nFile output disabled"
                return [(None, None, None, message, "", False, True)]
        self.output_file = filename
        message = 'Writing to file "%s"' % self.output_file
        return [(None, None, None, message, "", True, True)] 
Example 4
Project: pgcli   Author: dbcli   File:    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parse_service_info(service):
    service = service or os.getenv("PGSERVICE")
    service_file = os.getenv("PGSERVICEFILE")
    if not service_file:
        # try ~/.pg_service.conf (if that exists)
        if platform.system() == "Windows":
            service_file = os.getenv("PGSYSCONFDIR") + "\\pg_service.conf"
        elif os.getenv("PGSYSCONFDIR"):
            service_file = os.path.join(os.getenv("PGSYSCONFDIR"), ".pg_service.conf")
            service_file = expanduser("~/.pg_service.conf")
    if not service:
        # nothing to do
        return None, service_file
    service_file_config = ConfigObj(service_file)
    if service not in service_file_config:
        return None, service_file
    service_conf = service_file_config.get(service)
    return service_conf, service_file 
Example 5
Project: snowflake-connector-python   Author: snowflakedb   File:    License: Apache License 2.0 6 votes vote down vote up
def reset_cache_dir():
        # Cache directory
        if OCSPCache.CACHE_DIR is None:
            cache_root_dir = expanduser("~") or tempfile.gettempdir()
            if platform.system() == 'Windows':
                OCSPCache.CACHE_DIR = path.join(cache_root_dir, 'AppData', 'Local', 'Snowflake',
            elif platform.system() == 'Darwin':
                OCSPCache.CACHE_DIR = path.join(cache_root_dir, 'Library', 'Caches', 'Snowflake')
                OCSPCache.CACHE_DIR = path.join(cache_root_dir, '.cache', 'snowflake')
        logger.debug("cache directory: %s", OCSPCache.CACHE_DIR)

        if not path.exists(OCSPCache.CACHE_DIR):
                os.makedirs(OCSPCache.CACHE_DIR, mode=0o700)
            except Exception as ex:
                logger.debug('cannot create a cache directory: [%s], err=[%s]',
                             OCSPCache.CACHE_DIR, ex)
                OCSPCache.CACHE_DIR = None 
Example 6
Project: pulse2percept   Author: pulse2percept   File:    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_data_dir(data_dir=None):
    """Return the path of the pulse2percept data directory

    This directory is used to store the datasets retrieved by the data fetch
    utility functions to avoid downloading the data several times.

    By default, this is set to a directory called 'pulse2percept_data' in the
    user home directory.
    Alternatively, it can be set by a ``PULSE2PERCEPT_DATA`` environment
    variable or set programmatically by specifying a path.

    If the directory does not already exist, it is automatically created.

    data_dir : str | None
        The path to the pulse2percept data directory.
    if data_dir is None:
        data_dir = environ.get('PULSE2PERCEPT_DATA',
                               join('~', 'pulse2percept_data'))
    data_dir = expanduser(data_dir)
    if not exists(data_dir):
    return data_dir 
Example 7
Project: daudin   Author: terrycojones   File:    License: MIT License 6 votes vote down vote up
def __init__(self, outfp=sys.stdout, errfp=sys.stderr, debug=False,
                 printTracebacks=False, loadInitFile=True, shell=None,
        self.outfp = outfp
        self.errfp = errfp
        self.debug = debug
        self.printTracebacks = printTracebacks = shell or ['/bin/sh', '-c']
        self.usePtys = usePtys
        self.stdin = None
        self.lastStdin = None
        self.stdout = None
        self.pendingText = ''
        self.initFile = join(expanduser('~'), '')
        self.lastResultIsList = False
        self.local = self._getLocal()
        if loadInitFile:
        self.inPipeline = False 
Example 8
Project: screeps-stats   Author: screepers   File:    License: MIT License 6 votes vote down vote up
def getSettings():
    if not getSettings.settings:
        cwd = os.getcwd()
        path = cwd + '/.settings.yaml'

        if not os.path.isfile(path):
            path = cwd + '/.screeps_settings.yaml'

        if not os.path.isfile(path):
            path = expanduser('~') + '/.screeps_settings.yaml'

        if not os.path.isfile(path):
            path = '/vagrant/.screeps_settings.yaml'

        if not os.path.isfile(path):
            print 'no settings file found'
            return False

        with open(path, 'r') as f:
            getSettings.settings = yaml.load(f)

    return getSettings.settings 
Example 9
Project: magpy   Author: geomagpy   File:    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def extendarduinolist(self, idnum):
        from os.path import expanduser
        home = expanduser("~")

        martasdir = [path for path, dirs, files in os.walk(home) if path.endswith('MARTAS')][0]
        arduinosensorfile = os.path.join(martasdir,'arduinolist.csv')
        log.msg('Checking Arduinofile: %s' % arduinosensorfile)
        arduinolist = []
        sensorelement = []
            arduinolist = self.loadarduinolist(arduinosensorfile)
            sensorelement = [elem[0] for elem in arduinolist]
            print("Liste", sensorelement)
            log.msg('Arduino: No Sensor list so far -or- Error while getting sensor list')
        if not self.sensordict[idnum] in sensorelement:
            arduinolist.append([self.sensordict[idnum], self.keydict[idnum]])
Example 10
Project: magpy   Author: geomagpy   File:    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def sc():
    Show credentials

    sysuser = getuser()
    home = expanduser('~'+sysuser)
    # previously used expanduser('~') which does not work for root
    credentials = os.path.join(home,'.magpycred')
    print("Credentials: Overview of existing credentials:")
        dictslist = loadobj(credentials)
        print("Credentials: Could not load file")

    for d in dictslist:
    return dictslist 
Example 11
Project: rm-protection   Author: alanzchen   File:    License: MIT License 6 votes vote down vote up
def protect(protect_args=None):
    global c
    flags = ''
    option_end = False
    if not protect_args:
        protect_args = argv[1:]
    for arg in protect_args:
        if arg == '--':
            option_end = True
        elif (arg.startswith("-") and not option_end):
            flags = flags + arg[arg.rfind('-') + 1:]
        elif arg in c.invalid:
            pprint('"." and ".." may not be protected')
            path = abspath(expv(expu(arg)))
            evalpath = dirname(path) + "/." + basename(path) + c.suffix
            if not exists(path):
                pprint("Warning: " + path + " does not exist")
            with open(evalpath, "w") as f:
                question = input("Question for " + path + ": ")
                answer = input("Answer: ")
                f.write(question + "\n" + answer + "\n" + flags.upper()) 
Example 12
Project: pytorch_geometric   Author: rusty1s   File:    License: MIT License 6 votes vote down vote up
def __init__(self, root=None, transform=None, pre_transform=None,
        super(Dataset, self).__init__()

        if isinstance(root, str):
            root = osp.expanduser(osp.normpath(root))

        self.root = root
        self.transform = transform
        self.pre_transform = pre_transform
        self.pre_filter = pre_filter
        self.__indices__ = None

        if 'download' in self.__class__.__dict__.keys():

        if 'process' in self.__class__.__dict__.keys():
Example 13
Project: pyaff4   Author: aff4   File:    License: Apache License 2.0 6 votes vote down vote up
def loadMetadata(self, zip):
        # Load the turtle metadata.
        aff4cache = os.path.join(expanduser("~"), ".aff4")
        if not os.path.exists(aff4cache):
            except OSError as exc:  # Guard against race condition
                if exc.errno != errno.EEXIST:
        cached_turtle = os.path.join(aff4cache, "%s.hdt" % str(zip.urn)[7:])
        if not os.path.exists(cached_turtle):
            self.createHDTviaLib(zip, cached_turtle)

        if os.path.exists(cached_turtle):
            # assume we have a HDT cache of turtle at this point
            self.hdt = HDTDocument(cached_turtle)

    # this implementation currently not tested
    # and it is super ugly. We are materializing all triples just to
    # list all the subjects.
    # TODO: Implement subject iterator in pyHDT 
Example 14
Project: rankeval   Author: hpclab   File:    License: Mozilla Public License 2.0 6 votes vote down vote up
def __get_data_home__(data_home=None):
    Return the path of the rankeval data dir.
    This folder is used by some large dataset loaders to avoid
    downloading the data several times.
    By default the data dir is set to a folder named 'rankeval_data'
    in the user home folder.
    Alternatively, it can be set by the 'RANKEVAL_DATA' environment
    variable or programmatically by giving an explicit folder path. The
    '~' symbol is expanded to the user home folder.
    If the folder does not already exist, it is automatically created.
    if data_home is None:
        data_home = environ.get('RANKEVAL_DATA', join('~', 'rankeval_data'))
    data_home = expanduser(data_home)
    if not exists(data_home):
    return data_home 
Example 15
Project: GTDWeb   Author: lanbing510   File:    License: GNU General Public License v2.0 6 votes vote down vote up
def handle_template(self, template, subdir):
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path =
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 16
Project: ec2-gazua   Author: leejaycoke   File:    License: MIT License 6 votes vote down vote up
def key_file(self):
        if self.key_name is None:
            return None

        key_file = self.config['ssh-path'] + '/' + self.key_name
        key_path = expanduser(key_file)

        if isfile(key_path):
            return key_path

        if key_path.endswith('.pem'):
            raw_path = isfile(key_path.rsplit('.pem', 1)[0])
            return raw_path if isfile(raw_path) else None

        pem_path = key_path + '.pem'
        return pem_path if isfile(pem_path) else None 
Example 17
Project: CoinSwapCS   Author: AdamISZ   File:    License: GNU General Public License v3.0 6 votes vote down vote up
def lookup_appdata_folder():
    from os import path, environ
    if sys.platform == 'darwin':
        if "HOME" in environ:
            data_folder = path.join(os.environ["HOME"],
                                   "Library/Application support/",
                                   global_singleton.APPNAME) + '/'
            print("Could not find home folder")

    elif 'win32' in sys.platform or 'win64' in sys.platform:
        data_folder = path.join(environ['APPDATA'], global_singleton.APPNAME) + '\\'
        data_folder = path.expanduser(path.join("~",
                                    "." + global_singleton.APPNAME + "/"))
    return data_folder 
Example 18
Project: PE-HFT-Python   Author: PortfolioEffect   File:    License: GNU General Public License v3.0 6 votes vote down vote up
def util_setCredentials(username, password, apiKey, host='', port=443):
    # write credentials to file
    CLIENT_CONNECTION = {'username': username, 'password': password, 'apiKey': apiKey, 'host': host, 'port': port  }
    APPNAME = "ice9"
    if sys.platform == 'darwin':
        from AppKit import NSSearchPathForDirectoriesInDomains
        # NSApplicationSupportDirectory = 14
        # NSUserDomainMask = 1
        # True for expanding the tilde into a fully qualified path
        appdata = path.join(NSSearchPathForDirectoriesInDomains(14, 1, True)[0], APPNAME,'login.npy')
    elif sys.platform == 'win32':
        appdata = path.join(environ['APPDATA'], APPNAME,'login.npy')
        appdata = path.expanduser(path.join("~", "." + APPNAME,'login.npy')), CLIENT_CONNECTION) 
Example 19
Project: vedaseg   Author: Media-Smart   File:    License: Apache License 2.0 6 votes vote down vote up
def find_vcs_root(path, markers=('.git', )):
    """Finds the root directory (including itself) of specified markers.

        path (str): Path of directory or file.
        markers (list[str], optional): List of file or directory names.

        The directory contained one of the markers or None if not found.
    if osp.isfile(path):
        path = osp.dirname(path)

    prev, cur = None, osp.abspath(osp.expanduser(path))
    while cur != prev:
        if any(osp.exists(osp.join(cur, marker)) for marker in markers):
            return cur
        prev, cur = cur, osp.split(cur)[0]
    return None 
Example 20
Project: delocate   Author: matthew-brett   File:    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    parser = OptionParser(
        usage="%s WHEEL_FILENAME PATCH_FNAME\n\n" % sys.argv[0] + __doc__,
        version="%prog " + __version__)
        Option("-w", "--wheel-dir",
               action="store", type='string',
               help="Directory to store patched wheel (default is to "
               "overwrite input)"))
        Option("-v", "--verbose",
               help="Print input and output wheels"))
    (opts, args) = parser.parse_args()
    if len(args) != 2:
    wheel, patch_fname = args
    if opts.wheel_dir:
        wheel_dir = expanduser(opts.wheel_dir)
        if not exists(wheel_dir):
        wheel_dir = None
    if opts.verbose:
        print('Patching: {0} with {1}'.format(wheel, patch_fname))
    if wheel_dir:
        out_wheel = pjoin(wheel_dir, basename(wheel))
        out_wheel = wheel
    patch_wheel(wheel, patch_fname, out_wheel)
    if opts.verbose:
        print("Patched wheel {0} to {1}:".format(
            wheel, out_wheel)) 
Example 21
Project: b1tifi   Author: mh4x0f   File:    License: MIT License 5 votes vote down vote up
def main():
    folderDB = path.expanduser('~/.b1tifi-db')
    db_path = path.join(folderDB, 'b1tifi.db')
    if not path.exists(folderDB):
    shell = Console(db_path)
Example 22
Project: mealpy   Author: edmundmok   File:    License: MIT License 5 votes vote down vote up
def user_cache_dir():
    # stolen from pip.utils.appdirs.user_cache_dir
    from os import getenv
    from os.path import expanduser
    return getenv('XDG_CACHE_HOME', expanduser('~/.cache')) 
Example 23
Project: alibuild   Author: alisw   File:    License: GNU General Public License v3.0 5 votes vote down vote up
def enable_analytics():
  if exists(expanduser("~/.config/alibuild/disable-analytics")):
  if not exists(expanduser("~/.config/alibuild/analytics-uuid")):

# We do it in getstatusoutput because python makedirs can actually fail
# if one of the intermediate directories is not writeable. 
Example 24
Project:   Author: lord63   File:    License: MIT License 5 votes vote down vote up
def init():
    """Init config file."""
    default_config_path = path.join(
        (os.environ.get('TLDR_CONFIG_DIR') or path.expanduser('~')),
    if path.exists(default_config_path):
        click.echo("There is already a config file exists, "
                   "skip initializing it.")
        repo_path = click.prompt("Input the tldr repo path")
        repo_path = os.path.abspath(os.path.expanduser(repo_path))
        if not path.exists(repo_path):
            sys.exit("Repo path not exist, clone it first.")

        platform = click.prompt("Input your platform(linux, osx or sunos)")
        if platform not in ['linux', 'osx', 'sunos']:
            sys.exit("Platform should be linux, osx or sunos.")

        colors = {
            "description": "blue",
            "usage": "green",
            "command": "cyan"

        config = {
            "repo_directory": repo_path,
            "colors": colors,
            "platform": platform
        with open(default_config_path, 'w') as f:
            f.write(yaml.safe_dump(config, default_flow_style=False))

        click.echo("Initializing the config file at {0}".format(
Example 25
Project:   Author: lord63   File:    License: MIT License 5 votes vote down vote up
def get_config():
    """Get the configurations from .tldrrc and return it as a dict."""
    config_path = path.join(
        (os.environ.get('TLDR_CONFIG_DIR') or path.expanduser('~')),
    config_path = os.path.abspath(os.path.expanduser(config_path))
    if not path.exists(config_path):
        sys.exit("Can't find config file at: {0}. You may use `tldr init` "
                 "to init the config file.".format(config_path))

    with, encoding='utf-8') as f:
            config = yaml.safe_load(f)
        except yaml.scanner.ScannerError:
            sys.exit("The config file is not a valid YAML file.")

    supported_colors = ['black', 'red', 'green', 'yellow', 'blue',
                        'magenta', 'cyan', 'white']
    if not set(config['colors'].values()).issubset(set(supported_colors)):
        sys.exit("Unsupported colors in config file: {0}.".format(
            ', '.join(set(config['colors'].values()) - set(supported_colors))))
    if not path.exists(config['repo_directory']):
        sys.exit("Can't find the tldr repo, check the `repo_directory` "
                 "setting in config file.")

    return config 
Example 26
Project: HardRLWithYoutube   Author: MaxSobolMark   File:    License: MIT License 5 votes vote down vote up
def main(custom_args=[]):
    # configure logger, disable logging in child MPI processes (with rank > 0) 
    arg_parser = common_arg_parser()
    args, unknown_args = arg_parser.parse_known_args()
    extra_args = {}
    for arg in custom_args:
        if arg in vars(args).keys():
            vars(args)[arg] = custom_args[arg]
            extra_args[arg] = custom_args[arg]
    #extra_args = {k: parse(v) for k,v in parse_unknown_args(unknown_args).items()}

    if MPI is None or MPI.COMM_WORLD.Get_rank() == 0:
        rank = 0
        logger.configure(format_strs = ['stdout', 'tensorboard'])
        logger.configure(format_strs = ['stdout', 'tensorboard'])
        rank = MPI.COMM_WORLD.Get_rank()

    model, _ = train(args, extra_args)

    if args.save_path is not None and rank == 0:
        save_path = osp.expanduser(args.save_path)

        logger.log("Running trained model")
        env = build_env(args)
        obs = env.reset()
        while True:
            actions = model.step(obs)[0]
            obs, _, done, _  = env.step(actions)
            done = done.any() if isinstance(done, np.ndarray) else done

            if done:
                obs = env.reset() 
Example 27
Project: landmarkerio-server   Author: menpo   File:    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, n_dims, template_dir=None):
        self.n_dims = n_dims
        if template_dir is None:
            # try the user folder
            user_templates = p.expanduser(p.join('~', TEMPLATE_DINAME))
            if p.isdir(user_templates):
                template_dir = user_templates
                raise ValueError("No template dir provided and "
                                 "{} doesn't exist".format(user_templates))
        self.template_dir = Path(p.abspath(p.expanduser(template_dir)))
        print ('templates: {}'.format(self.template_dir)) 
Example 28
Project: landmarkerio-server   Author: menpo   File:    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def filepath_as_asset_id_under_dir(asset_dir):
    # find the filepath under asset_dir and return the full path as an asset id
    asset_dir = Path(abspath(expanduser(asset_dir)))

    def path_as_asset_id(fp):
        return '__'.join(Path(fp).relative_to(asset_dir).parts)

    return path_as_asset_id 
Example 29
Project: landmarkerio-server   Author: menpo   File:    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ensure_asset_dir(asset_dir):
    asset_dir = p.abspath(p.expanduser(asset_dir))
    if not p.isdir(asset_dir):
        raise ValueError('{} is not a directory.'.format(asset_dir))
    print ('assets:    {}'.format(asset_dir))
    return asset_dir

Example 30
Project: landmarkerio-server   Author: menpo   File:    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ensure_cache_dir(cache_dir):
    cache_dir = p.abspath(p.expanduser(cache_dir))
    if not p.isdir(cache_dir):
        print("Warning the cache dir does not exist - creating...")
    print ('cache:     {}'.format(cache_dir))
    return cache_dir