本文整理匯總了Python中os.path.expandvars方法的典型用法代碼示例。如果您正苦於以下問題:Python path.expandvars方法的具體用法?Python path.expandvars怎麽用?Python path.expandvars使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類os.path
的用法示例。
在下文中一共展示了path.expandvars方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: protect
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
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')
else:
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())
示例2: tokenize_files
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def tokenize_files(files_pattern: str, output: str, options: dict = None) -> None:
if options is None:
options = {}
files_pattern = path.expandvars(path.expanduser(files_pattern))
files = glob(files_pattern, recursive=True)
total_count = len(files)
logging.info("starting to tokenize %s files", total_count)
queue = Queue(100) # type: Queue[QueueItem]
write_results_process = Process(target=write_results, args=(queue, output, total_count))
write_results_process.start()
pool = Pool(None, process_file_init, [queue, options])
pool.map(process_file, files)
pool.close()
pool.join()
logging.debug("pool done, waiting for write results process")
queue.put(None)
write_results_process.join()
logging.info("successfully processed %s files", queue.get())
示例3: expandpath
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def expandpath(path):
"""
Shell-like environment variable and tilde path expansion.
Less aggressive than truepath. Only expands environs and tilde. Does not
change relative paths to absolute paths.
Args:
path (str | PathLike): string representation of a path
Returns:
str : expanded path
Example:
>>> import ubelt as ub
>>> assert normpath(ub.expandpath('~/foo')) == join(ub.userhome(), 'foo')
>>> assert ub.expandpath('foo') == 'foo'
"""
path = expanduser(path)
path = expandvars(path)
return path
示例4: __find_config_files
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def __find_config_files(pattern="*.py", rcfile=False):
""" Finds configuration files
Looks for files with a given pattern in the following directory:
- config subdirectory of the pylada package
- directory pointed to by the "PYLADA_CONFIG_DIR" environment variable, if it exists
- in "~/.pylada" if it exist and is a directory
"""
from os.path import expandvars, expanduser
from py.path import local
from os import environ
filenames = local(__file__).dirpath("config").listdir(fil=pattern, sort=True)
for envdir in ['PYLADA_CONFIG_DIR', 'LADA_CONFIG_DIR']:
if envdir in environ:
configdir = expandvars(expanduser(environ[envdir]))
filenames += local(configdir).listdir(fil=pattern, sort=True)
pylada = local(expanduser("~/.pylada"))
if pylada.isdir():
filenames += pylada.listdir(fil=pattern, sort=True)
elif rcfile and pylada.check(file=True):
filenames += [pylada]
return filenames
示例5: envvar
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def envvar(self):
""" Fixed point for relative directory. """
from os.path import expanduser, expandvars, normpath
from . import local_path
from .. import global_root
if self._envvar is None:
if global_root is None:
return '/'
if '$' not in global_root and '~' not in global_root:
return normpath(global_root)
# Need to figure it out.
try:
local_path(global_root).ensure(dir=True)
return str(local_path(global_root))
except OSError as e:
raise IOError('Could not figure out directory {0}.\n'
'Caught error OSError {1.errno}: {1.message}'
.format(global_root, e))
return normpath(expandvars(expanduser(self._envvar)))
示例6: path
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def path(self, value):
from os.path import relpath, expandvars, expanduser, abspath
from os import getcwd
if value is None:
value = getcwd()
if isinstance(value, tuple) and len(value) == 2:
self.envvar = value[0]
self.relative = value[1]
return
if len(value.rstrip().lstrip()) == 0:
value = getcwd()
# This is a python bug where things don't work out if the root path is '/'.
# Seems corrected after 2.7.2
if self.envvar == '/':
self._relative = abspath(expanduser(expandvars(value)))[1:]
else:
self._relative = relpath(expanduser(expandvars(value)), self.envvar)
self.hook(self.path)
示例7: __init__
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def __init__(self, app, cork, redis, session_opts, access_cls=None, access_redis=None):
super(RedisSessionMiddleware, self).__init__(app, session_opts['session.key'])
self.redis = redis
self.access_redis = access_redis
self.cork = cork
self.auto_login_user = os.environ.get('AUTO_LOGIN_USER')
self.secret_key = expandvars(session_opts['session.secret'])
self.key_template = session_opts['session.key_template']
self.long_sessions_key = session_opts['session.long_sessions_key']
self.durations = session_opts['session.durations']
self.access_cls = access_cls
示例8: expand_all
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def expand_all(input_path,
wildcard_values={},
current_folder='',
expand_globbing=True):
"""Expand everything in this path.
This returns a list of canonical paths.
"""
expanded_path = path.expandvars(input_path)
expanded_path = sublime.expand_variables(
expanded_path, wildcard_values)
expanded_path = File.canonical_path(expanded_path, current_folder)
if not expanded_path:
return []
if expand_globbing:
from glob import glob
all_paths = glob(expanded_path)
else:
all_paths = [expanded_path]
if len(all_paths) > 0 and all_paths[0] != input_path:
log.debug("Populated '%s' to '%s'", input_path, all_paths)
return all_paths
elif expanded_path != input_path:
log.debug("Populated '%s' to '%s'", input_path, expanded_path)
return [expanded_path]
示例9: main
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def main():
parser = ArgumentParser(prog='nuclio', description=__doc__)
sub = parser.add_subparsers()
dp = sub.add_parser('deploy')
populate_deploy_parser(dp)
dp.set_defaults(func=do_deploy)
delp = sub.add_parser('del')
delete_parser(delp)
delp.set_defaults(func=do_delete)
exargs = [path.expandvars(arg) for arg in sys.argv[1:]]
args = parser.parse_args(exargs)
try:
args.func(args)
except AttributeError as err:
print('Unrecognized command or error: ', err)
parser.print_help()
示例10: parse_config_line
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def parse_config_line(line):
# a.b.c = "x"
# a += 17
match = re.search(r'(\w+(\.\w+)*)\s*(\+?=)\s*?(.+)', line)
if not match:
raise ValueError('bad config line - {!r}'.format(line))
key = match.group(1)
op = match.group(3)
value = match.group(4).strip()
value = path.expandvars(value)
try:
value = json.loads(value)
except (SyntaxError, ValueError):
raise ValueError(
'cant eval config value: "{}" in line: {}'.format(value, line))
return key, op, value
示例11: parse_export_line
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def parse_export_line(args):
parser = ArgumentParser(prog='%nuclio', add_help=False)
parser.add_argument('--output_dir', '-o', default='')
parser.add_argument('--tag', '-t', default='')
parser.add_argument('--name', '-n', default='')
parser.add_argument('--project', '-p', default='')
parser.add_argument('--handler')
parser.add_argument('--env', '-e', default=[], action='append')
parser.add_argument('--archive', '-a', action='store_true', default=False)
parser.add_argument('--verbose', '-v', action='store_true', default=False)
parser.add_argument('--kind', default=None)
if isinstance(args, str):
args = path.expandvars(args)
args = shlex.split(args)
return parser.parse_known_args(args)
示例12: cmd
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def cmd(line, cell):
"""Run a command, add it to "build.Commands" in exported configuration.
Examples:
In [1]: %nuclio cmd pip install chardet==1.0.1
In [2]: %%nuclio cmd
...: apt-get install -y libyaml-dev
...: pip install pyyaml==3.13
If you'd like to only to add the instructions to function.yaml without
running it locally, use the '--config-only' or '-c' flag
In [3]: %nuclio cmd --config-only apt-get install -y libyaml-dev
"""
if line.startswith('--config-only') or line.startswith('-c'):
return
ipy = get_ipython()
if line:
ipy.system(path.expandvars(line))
for line in cell_lines(cell):
ipy.system(path.expandvars(line))
示例13: _cygexpath
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def _cygexpath(drive, path):
if osp.isabs(path) and not drive:
## Invoked from `cygpath()` directly with `D:Apps\123`?
# It's an error, leave it alone just slashes)
p = path
else:
p = path and osp.normpath(osp.expandvars(osp.expanduser(path)))
if osp.isabs(p):
if drive:
# Confusing, maybe a remote system should expand vars.
p = path
else:
p = cygpath(p)
elif drive:
p = '/cygdrive/%s/%s' % (drive.lower(), p)
return p.replace('\\', '/')
示例14: displaypath
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def displaypath(self, pathvar, entryfield):
entryfield['state'] = tk.NORMAL # must be writable to update
entryfield.delete(0, tk.END)
if platform=='win32':
start = pathvar.get().lower().startswith(config.home.lower()) and len(config.home.split('\\')) or 0
display = []
components = normpath(pathvar.get()).split('\\')
buf = ctypes.create_unicode_buffer(MAX_PATH)
pidsRes = ctypes.c_int()
for i in range(start, len(components)):
try:
if (not SHGetLocalizedName('\\'.join(components[:i+1]), buf, MAX_PATH, ctypes.byref(pidsRes)) and
LoadString(ctypes.WinDLL(expandvars(buf.value))._handle, pidsRes.value, buf, MAX_PATH)):
display.append(buf.value)
else:
display.append(components[i])
except:
display.append(components[i])
entryfield.insert(0, '\\'.join(display))
elif platform=='darwin' and NSFileManager.defaultManager().componentsToDisplayForPath_(pathvar.get()): # None if path doesn't exist
if pathvar.get().startswith(config.home):
display = ['~'] + NSFileManager.defaultManager().componentsToDisplayForPath_(pathvar.get())[len(NSFileManager.defaultManager().componentsToDisplayForPath_(config.home)):]
else:
display = NSFileManager.defaultManager().componentsToDisplayForPath_(pathvar.get())
entryfield.insert(0, '/'.join(display))
else:
if pathvar.get().startswith(config.home):
entryfield.insert(0, '~' + pathvar.get()[len(config.home):])
else:
entryfield.insert(0, pathvar.get())
entryfield['state'] = 'readonly'
示例15: resolve_from_str
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import expandvars [as 別名]
def resolve_from_str(input, root):
assert not isinstance(input, Path), "would break on py2"
root = Path(root)
input = expanduser(input)
input = expandvars(input)
if isabs(input):
return Path(input)
else:
return root.joinpath(input)