本文整理汇总了Python中os.path.expanduser函数的典型用法代码示例。如果您正苦于以下问题:Python expanduser函数的具体用法?Python expanduser怎么用?Python expanduser使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了expanduser函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_sys_path
def get_sys_path(rcpath, app_name, section_name=None):
"""Return a folder path if it exists.
First will check if it is an existing system path, if it is, will return it
expanded and absoluted.
If this fails will look for the rcpath variable in the app_name rcfiles or
exclusively within the given section_name, if given.
Parameters
----------
rcpath: str
Existing folder path or variable name in app_name rcfile with an
existing one.
section_name: str
Name of a section in the app_name rcfile to look exclusively there for
variable names.
app_name: str
Name of the application to look for rcfile configuration files.
Returns
-------
sys_path: str
A expanded absolute file or folder path if the path exists.
Raises
------
IOError if the proposed sys_path does not exist.
"""
# first check if it is an existing path
if op.exists(rcpath):
return op.realpath(op.expanduser(rcpath))
# look for the rcfile
try:
settings = rcfile(app_name, section_name)
except:
raise
# look for the variable within the rcfile configutarions
try:
sys_path = op.expanduser(settings[rcpath])
except KeyError:
raise IOError('Could not find an existing variable with name {0} in'
' section {1} of {2}rc config setup. Maybe it is a '
' folder that could not be found.'.format(rcpath,
section_name,
app_name))
# found the variable, now check if it is an existing path
else:
if not op.exists(sys_path):
raise IOError('Could not find the path {3} indicated by the '
'variable {0} in section {1} of {2}rc config '
'setup.'.format(rcpath, section_name, app_name,
sys_path))
# expand the path and return
return op.realpath(op.expanduser(sys_path))
示例2: get_field
def get_field(field, directory, partitions, mesh, surface = "average"):
"""
Get the values of a field from Elmer's output on either the top or
bottom surface or averaged throughout a vertical column.
Paramters:
=========
field: name of the field to get, e.g. "beta", "pressure", "velod 1"
directory: path to the files output by Elmer
partitions: the number of partitions of the Elmer mesh
mesh: a matplotlib.tri object encapsulating the original Triangle
mesh used to generated the Elmer mesh
surface: either "top", "bottom" or "average"; the layer we want to
get the field from
Outputs:
=======
q: the desired field, reconciled to the node ordering of `mesh`
"""
filename = "Test_Robin_Beta.result"
data = get_variable(field,
expanduser(directory),
expanduser(filename),
partitions)
x, y, q = get_layer(data, surface)
permutation = reconcile_elmer_with_mesh(mesh.x, mesh.y, x, y)
return q[permutation]
示例3: load_config
def load_config(usr_cfg, def_cfg=None):
cfg = ConfigObj()
cfg.merge(ConfigObj(def_cfg, interpolation=False))
cfg.merge(ConfigObj(expanduser(usr_cfg), interpolation=False, encoding='utf-8'))
cfg.filename = expanduser(usr_cfg)
return cfg
示例4: main
def main():
from sys import argv
if len(argv) < 4:
print "Insufficient arguments!"
print "Proper Usage: %s [db_path] [experiment_path] [offset_file]"
return
db_path = path.expanduser(argv[1])
db_man = io.ImageDbManager(db_path, readonly=False)
experiment_path = path.expanduser(argv[2])
meta_man = io.MetadataManager(experiment_path)
offset_path = path.expanduser(argv[3])
offsets = json.load(open(offset_path))
for i, offset in enumerate(offsets):
print "Updating image %d/%d" % (i, len(offsets))
key = offset['vsi_path'][2:]
try:
image = db_man.get_image(key)
image.region_map_offset = offset['pad_size']
metadata = meta_man.get_entry_by_attribute('vsiPath', key)
region_map = io.load_mhd(path.join(experiment_path, metadata['registeredAtlasLabelsPath']))[0]
hemisphere_map = io.load_mhd(path.join(experiment_path, metadata['registeredHemisphereLabelsPath']))[0]
image.region_map = numpy.rot90(region_map, k=2)
image.hemisphere_map = numpy.rot90(hemisphere_map, k=2)
db_man.add_image(image)
except:
print "Failed to update image with key: %s" % key
示例5: find_config_files
def find_config_files(metadata_or_path, additional_files=None, ignore_system_config=False,
exclusive_config_files=None):
"""Find files to load variables from. Note that order here determines clobbering.
Later files clobber earlier ones. order is user-wide < cwd < recipe dir < additional files"""
files = [
os.path.abspath(os.path.expanduser(config_file))
for config_file in (exclusive_config_files or [])
]
if not ignore_system_config and not exclusive_config_files:
if cc_conda_build.get('config_file'):
system_path = abspath(expanduser(expandvars(cc_conda_build['config_file'])))
else:
system_path = os.path.join(expanduser('~'), "conda_build_config.yaml")
if os.path.isfile(system_path):
files.append(system_path)
cwd = os.path.join(os.getcwd(), 'conda_build_config.yaml')
if os.path.isfile(cwd):
files.append(cwd)
if hasattr(metadata_or_path, 'path'):
recipe_config = os.path.join(metadata_or_path.path, "conda_build_config.yaml")
else:
recipe_config = os.path.join(metadata_or_path, "conda_build_config.yaml")
if os.path.isfile(recipe_config):
files.append(recipe_config)
if additional_files:
files.extend([os.path.expanduser(additional_file) for additional_file in additional_files])
return files
示例6: main
def main(argv):
manifestPath = op.expanduser(argv[1])
moduleDepPath = op.expanduser(argv[2])
otbDir = op.expanduser(argv[3])
appManifest = argv[4]
csvAppDepends = argv[5]
#app_dir = op.join(otbDir,"Applications")
# Standard Manifest parsing, extract simple and full dependencies
[groups,moduleList,sourceList] = manifestParser.parseManifest(manifestPath)
depList = manifestParser.parseDependList(moduleDepPath)
fullDepList = manifestParser.buildFullDep(depList)
[appGroups,appModuleList,appSourceList] = manifestParser.parseManifest(appManifest)
# add application sources to sourceList
for item in appSourceList:
sourceList[item] = appSourceList[item]
appDependsList = manifestParser.buildSimpleDep(otbDir,appModuleList,sourceList)
#manifestParser.printDepList(appDependsList)
manifestParser.outputCSVEdgeList(appDependsList,csvAppDepends)
示例7: test_default_directories3
def test_default_directories3(alfred3):
"""Default directories (Alfred 3)"""
from os.path import expanduser
_test_default_directories(
expanduser('~/Library/Application Support/Alfred 3/Workflow Data/'),
expanduser('~/Library/Caches/com.runningwithcrayons.Alfred-3/'
'Workflow Data/'))
示例8: find_executable
def find_executable(executable, include_others=True):
# backwards compatibility
global dir_paths
if include_others:
if sys.platform == 'win32':
dir_paths = [join(sys.prefix, 'Scripts'),
'C:\\cygwin\\bin']
else:
dir_paths = [join(sys.prefix, 'bin')]
else:
dir_paths = []
dir_paths.extend(os.environ['PATH'].split(os.pathsep))
for dir_path in dir_paths:
if sys.platform == 'win32':
for ext in ('.exe', '.bat', ''):
path = join(dir_path, executable + ext)
if isfile(path):
return path
else:
path = join(dir_path, executable)
if isfile(expanduser(path)):
return expanduser(path)
return None
示例9: parse_config_file
def parse_config_file(text):
config = configparser.RawConfigParser()
# default options
config.add_section("Save")
config.set("Save", "magnets", "false")
config.set("Save", "torrents", "false")
config.set("Save", "directory", os.getcwd())
config.add_section("LocalDB")
config.set("LocalDB", "enabled", "false")
config.set("LocalDB", "path", expanduser("~/downloads/pirate-get/db"))
config.add_section("Misc")
# TODO: try to use https://docs.python.org/3/library/configparser.html#configparser.BasicInterpolation for interpolating in the command
config.set("Misc", "openCommand", "")
config.set("Misc", "transmission", "false")
config.set("Misc", "colors", "true")
config.read_string(text)
# expand env variables
directory = expanduser(expandvars(config.get("Save", "Directory")))
path = expanduser(expandvars(config.get("LocalDB", "path")))
config.set("Save", "Directory", directory)
config.set("LocalDB", "path", path)
return config
示例10: next
def next(self, value, index, region):
file = self.options.get("file", None)
folder = self.options.get("folder", None)
script = self.options.get("script", None)
sugar = self.options.get("sugar", True)
if file:
folder = folder if folder else expanduser("~")
file = normpath(join(folder, file))
if isfile(file):
with open(file, "r") as f:
script = f.read()
elif script and sugar:
if not 'return ' in script and not ';' in script:
script = "value = " + script
script = 'var result=(function(value, index, begin, end){{{SCRIPT};return value;}}({VALUE}, {INDEX}, {BEGIN}, {END}));process.stdout.write('' + result);'.format(
SCRIPT=script,
VALUE=json.dumps(value),
INDEX=index,
BEGIN=region.a,
END=region.b
)
if not script:
print('No script found, canceling')
return None
cmd = "/usr/local/bin/node"
cwd = expanduser("~")
print('Running nodejs script:', script)
proc = subprocess.Popen([cmd, '-e', script], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
result = proc.communicate()[0]
if proc.returncode == 0:
print('script result:', result.decode('UTF-8'))
return result.decode('UTF-8')
else:
print('error while processing script:', result.decode('UTF-8'))
return None
示例11: _configure
def _configure(self):
""" Configure the ssh parameters from the config file. """
configfile = expanduser("~/.ssh/config")
if not isfile(configfile):
raise GerritError("ssh config file '%s' does not exist" %
configfile)
config = SSHConfig()
config.parse(open(configfile))
data = config.lookup(self.hostname)
if not data:
raise GerritError("No ssh config for host %s" % self.hostname)
if 'hostname' not in data or 'port' not in data or 'user' not in data:
raise GerritError("Missing configuration data in %s" % configfile)
self.hostname = data['hostname']
self.username = data['user']
if 'identityfile' in data:
key_filename = abspath(expanduser(data['identityfile'][0]))
if not isfile(key_filename):
raise GerritError("Identity file '%s' does not exist" %
key_filename)
self.key_filename = key_filename
try:
self.port = int(data['port'])
except ValueError:
raise GerritError("Invalid port: %s" % data['port'])
if 'proxycommand' in data:
self.proxy = ProxyCommand(data['proxycommand'])
示例12: _config_files
def _config_files(dointeractive=False):
from os.path import exists, expanduser, expandvars, dirname, join
from glob import iglob
from os import environ
# pattern to distinguish files to run only in interactive mode.
# these files are loaded by the pylada-ipython extension itself.
pattern = "*.py" if not dointeractive else "ipy_*.py"
# dictionary with stuff we want defined when reading config files.
global_dict = {"pyladamodules": __all__}
local_dict = {}
# first configuration files installed with pylada.
for filename in iglob(join(join(dirname(__file__), "config"), pattern)):
if dointeractive == False and filename[:4] == 'ipy_': continue
execfile(filename, global_dict, local_dict)
# then configuration files installed in a global config directory.
if "PYLADA_CONFIG_DIR" in environ:
for directory in environ["PYLADA_CONFIG_DIR"].split(':'):
for filename in iglob(join(directory, pattern)):
if dointeractive == False and filename[:4] == 'ipy_': continue
execfile(filename, global_dict, local_dict)
# then user configuration file.
if exists(expandvars(expanduser('~/.pylada'))):
execfile(expandvars(expanduser('~/.pylada')), global_dict, local_dict)
return local_dict
示例13: complete_files
def complete_files(self, text, state):
str_delim = text[0]
path = text[1:]
if path.startswith("~/"):
path = expanduser("~/") + path[2:]
elif path.startswith("~"):
i = path.find(pathsep)
if i > 0:
path = expanduser(path[:i]) + path[i:]
else:
return [
str_delim + "~" + i[0] + pathsep
for i in getpwall()
if i[0].startswith(path[1:])
][state]
dir, fname = splitpath(path)
if not dir:
dir = os.curdir
return [
str_delim + joinpath(dir, i)
for i in os.listdir(dir)
if i.startswith(fname)
][state]
示例14: read_process_write
def read_process_write(self, input, input_filename, output_filename):
"""Reads input, executes any processing and writes output."""
# Read input if needed.
if input is None and not self._no_input:
if input_filename is None:
raise RuntimeError('No file to read from.')
input_filename = self.input_root + input_filename
input_filename = path.expanduser(input_filename)
logger.info("%s reading data from file %s." %
(self.__class__.__name__, input_filename))
input = self.read_input(input_filename)
# Analyse.
if self._no_input:
if not input is None:
# This should never happen. Just here to catch bugs.
raise RuntimeError("Somehow `input` was set.")
output = self.process()
else:
output = self.process(input)
# Write output if needed.
if self.output_root != 'None' and not output is None:
if output_filename is None:
raise RuntimeError('No file to write to.')
output_filename = self.output_root + output_filename
output_filename = path.expanduser(output_filename)
logger.info("%s writing data to file %s." %
(self.__class__.__name__, output_filename))
output_dirname = os.path.dirname(output_filename)
if not os.path.isdir(output_dirname):
os.makedirs(output_dirname)
self.write_output(output_filename, output)
return output
示例15: loggerInit
def loggerInit():
debuglog = logging.getLogger('GGPODebug')
debuglog.setLevel(logging.INFO)
fh = logging.handlers.RotatingFileHandler(
os.path.join(expanduser("~"), 'fightcade-debug.log'), mode='a', maxBytes=500000, backupCount=10)
if Settings.value(Settings.DEBUG_LOG):
fh.setLevel(logging.INFO)
else:
fh.setLevel(logging.ERROR)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
debuglog.addHandler(fh)
debuglog.addHandler(ch)
def handle_exception(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
debuglog.error("<Uncaught exception>", exc_info=(exc_type, exc_value, exc_traceback))
sys.excepthook = handle_exception
if __name__ == "__main__":
raise RuntimeError("Test unhandled")
userlog = logging.getLogger('GGPOUser')
userlog.setLevel(logging.INFO)
fh = logging.handlers.RotatingFileHandler(
os.path.join(expanduser("~"), 'fightcade.log'), mode='a', maxBytes=500000, backupCount=10)
fh.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(message)s', "%Y-%m-%d %H:%M")
fh.setFormatter(formatter)
userlog.addHandler(fh)