本文整理汇总了Python中os.expanduser方法的典型用法代码示例。如果您正苦于以下问题:Python os.expanduser方法的具体用法?Python os.expanduser怎么用?Python os.expanduser使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.expanduser方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: saverc
# 需要导入模块: import os [as 别名]
# 或者: from os import expanduser [as 别名]
def saverc(filename, dat, overwrite=False):
'''
saverc(filename, d) saves the given configuration dictionary d to the given filename in JSON
format. If d is not a dictionary or if filename already exists or cannot be created, an error
is raised. This funciton does not create directories.
The optional argument overwrite (default: False) may be passed as True to overwrite files that
already exist.
'''
filename = os.path.expanduser(os.path.expandvars(filename))
if not overwrite and os.path.isfile(filename):
raise ValueError('Given filename %s already exists' % filename)
if not pimms.is_map(dat):
try: dat = dict(dat)
except Exception: raise ValueError('Given config data must be a dictionary')
with open(filename, 'w') as fl:
json.dump(dat, fl, sort_keys=True)
return filename
# the private class that handles all the details...
示例2: rc
# 需要导入模块: import os [as 别名]
# 或者: from os import expanduser [as 别名]
def rc():
'''
config.rc() yields the data imported from the Neuropythy rc file, if any.
'''
if config._rc is None:
# First: We check to see if we have been given a custom nptyhrc file:
npythyrc_path = os.path.expanduser('~/.npythyrc')
if 'NPYTHYRC' in os.environ:
npythyrc_path = os.path.expanduser(os.path.expandvars(os.environ['NPYTHYRC']))
# the default config:
if os.path.isfile(npythyrc_path):
try:
config._rc = loadrc(npythyrc_path)
config._rc['npythyrc_loaded'] = True
except Exception as err:
warnings.warn('Could not load neuropythy RC file: %s' % npythyrc_path)
config._rc = {'npythyrc_loaded':False,
'npythyrc_error': err}
else:
config._rc = {'npythyrc_loaded':False}
config._rc['npythyrc'] = npythyrc_path
return config._rc
示例3: load_credentials
# 需要导入模块: import os [as 别名]
# 或者: from os import expanduser [as 别名]
def load_credentials(flnm):
'''
load_credentials(filename) yields the credentials stored in the given file as a tuple
(key, secret). The file must contain <key>:<secret> on a single line. If the file does not
contain valid credentials, then an exception is raised. Yields (key, secret).
Optionally, if the file contains exactly two lines, then the key is taken as the first line and
the secret is taken as the second line. This can be used if ':' is a valid character in either
the key or secret for a particular service.
Note that if the key/secret are more than 8kb in size, this function's behaviour is undefined.
'''
flnm = os.path.expanduser(os.path.expandvars(flnm))
with open(flnm, 'r') as fl: dat = fl.read(1024 * 8)
# see if its a 2-line file:
try: return str_to_credentials(dat)
except Exception: raise ValueError('File %s does not contain a valid credential string' % flnm)
示例4: resolve_pathname
# 需要导入模块: import os [as 别名]
# 或者: from os import expanduser [as 别名]
def resolve_pathname(self, pathname):
"""Resolve a pathname relative to the competition's base directory.
Accepts None, returning it.
Applies os.expanduser to the pathname.
Doesn't absolutise or normalise the resulting pathname.
Raises ValueError if it can't handle the pathname.
"""
if pathname is None:
return None
if pathname == "":
raise ValueError("empty pathname")
try:
pathname = os.path.expanduser(pathname)
except Exception:
raise ValueError("bad pathname")
try:
return os.path.join(self.base_directory, pathname)
except Exception:
raise ValueError(
"relative path supplied but base directory isn't set")
示例5: expand_user
# 需要导入模块: import os [as 别名]
# 或者: from os import expanduser [as 别名]
def expand_user(token: str) -> str:
"""
Wrap os.expanduser() to support expanding ~ in quoted strings
:param token: the string to expand
"""
if token:
if is_quoted(token):
quote_char = token[0]
token = strip_quotes(token)
else:
quote_char = ''
token = os.path.expanduser(token)
# Restore the quotes even if not needed to preserve what the user typed
if quote_char:
token = quote_char + token + quote_char
return token
示例6: loadrc
# 需要导入模块: import os [as 别名]
# 或者: from os import expanduser [as 别名]
def loadrc(filename):
'''
loadrc(filename) yields the dict object encoded in JSON in the given filename; if the filename
does not exist or does not contain a valid JSON dict, then an error is raised.
'''
filename = os.path.expanduser(os.path.expandvars(filename))
if not os.path.isfile(filename): raise ValueError('Filename %s does not exist' % filename)
with open(filename, 'r') as fl:
dat = json.load(fl)
try: dat = dict(dat)
except Exception: raise ValueError('Given file %s does not contain a dictionary' % filename)
return dat
示例7: declare_path
# 需要导入模块: import os [as 别名]
# 或者: from os import expanduser [as 别名]
def declare_path(name,
rc_name=None, environ_name=None, filter=None, default_value=None, merge=None,
fail_value=None):
'''
config.declare_path(...) is equivalent to config.declare(...) except that it requires in
addition that the value found for the config item be an existing file or dir on the local
filesystem. Only if this is true is the value passed to any provided filter.
This function (similar to config.declare_file and config.declare_dir) is generally expected
to return some data--the contents of the path--not the path-name itself. For this reason
the handling of the default_value argument is expanded relative to that of config.declare().
If no value is provided or if all provided values are either not paths or fail the filter,
then the default_value is checked (as a path); if this also fails then the fail_value is
used as the config value. By default this is None, but note that by using a filter function
that loads the provided path (which will be guaranteed to exist) and yields the data along
with a fail_value that resembles 'default' data, one can effectively guarantee that data is
either loaded from a source on the filesystem or is in a coherent default state.
See also config.declare_dir and config.declare_file.
'''
def _check_path(path):
if path is None:
# check the default_value...
if default_value is not None:
try: return _check_path(default_value)
except Exception: pass
return None
path = os.path.expanduser(os.path.expandvars(path))
if not os.path.exists(path): raise ValueError('Provided file not found: %s' % path)
path = os.path.abspath(path)
try: return path if filter is None else filter(path)
except Exception: return fail_value
return config.declare(name, rc_name=rc_name, environ_name=environ_name, filter=_check_path,
default_value=None, merge=merge)
示例8: get_cache_base
# 需要导入模块: import os [as 别名]
# 或者: from os import expanduser [as 别名]
def get_cache_base(suffix=None):
"""
Return the default base location for distlib caches. If the directory does
not exist, it is created. Use the suffix provided for the base directory,
and default to '.distlib' if it isn't provided.
On Windows, if LOCALAPPDATA is defined in the environment, then it is
assumed to be a directory, and will be the parent directory of the result.
On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
directory - using os.expanduser('~') - will be the parent directory of
the result.
The result is just the directory '.distlib' in the parent directory as
determined above, or with the name specified with ``suffix``.
"""
if suffix is None:
suffix = '.distlib'
if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
result = os.path.expandvars('$localappdata')
else:
# Assume posix, or old Windows
result = os.path.expanduser('~')
# we use 'isdir' instead of 'exists', because we want to
# fail if there's a file with that name
if os.path.isdir(result):
usable = os.access(result, os.W_OK)
if not usable:
logger.warning('Directory exists but is not writable: %s', result)
else:
try:
os.makedirs(result)
usable = True
except OSError:
logger.warning('Unable to create %s', result, exc_info=True)
usable = False
if not usable:
result = tempfile.mkdtemp()
logger.warning('Default location unusable, using %s', result)
return os.path.join(result, suffix)
示例9: testbin_to_fpath
# 需要导入模块: import os [as 别名]
# 或者: from os import expanduser [as 别名]
def testbin_to_fpath():
global testbin
if testbin.endswith('-win') or testbin.endswith('-windows'):
testbin = testbin + '.exe'
tmp = os.path.join('testbins', testbin)
if '~' in tmp:
tmp = os.expanduser(tmp)
tmp = os.path.abspath(tmp)
return tmp
# 'helloworld_armv7-android' -> '/data/local/tmp/helloworld_armv7-android'