我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用os.path.expandvars()。
def test_args_ca_certi_path_from_command_line(self): cli_args = argparse.Namespace(cacert="~/review-rot/", debug=False, format=None, insecure=False, reverse=False, duration=None, state=None, value=None) config_args = self.config['test8']['arguments'] arguments = get_arguments(cli_args, config_args, self.choices) # Arguments 'cacert' is given in config. # But 'cacert' is also provided as CLI arguments. So CLI arguments has # higher precedence. Since insecure is False, ssl_verify should have # CA Certificate path ssl_result = arguments.get('ssl_verify') == \ expanduser(expandvars(vars(cli_args).get('cacert'))) self.assertTrue(ssl_result)
def log(msg, type = "info"): """ Write information to log file. type: info, warn, error """ log_dir = path.expandvars('$HOME') + "/.kreminder/log" log_file = log_dir + "/kreminder.log" if not path.exists(log_dir): makedirs(log_dir) curr_time = "[ " + strftime("%Y-%m-%d %H:%M:%S", localtime()) + " " + " ]" if type == "info": content = curr_time + " <INFO> " + msg + "\n" elif type == "warn": content = curr_time + " <WARNNING> " + msg + "\n" elif type == "error": content = curr_time + " <ERROR> " + msg + "\n" else: content = curr_time + "??????????\n" file_object = open(log_file, "a") file_object.write(content) file_object.close()
def extract_info(filename, extractor='youtube-dl'): """Return list of entries extracted from a path or URL using specified extractor. If an error occur during the extraction, return None. The extractor could be either 'json', 'mpv' or 'youtube-dl' and fallback to 'youtube-dl'. """ if isfile(expanduser(expandvars(filename))): filename = abspath(expanduser(expandvars(filename))) if extractor == 'json': return json_extract_info(filename) elif extractor == 'mpv': return mpv_extract_info(filename) else: return ytdl_extract_info(filename)
def __init__(self, dst, disk_type, disk, do_compress): """ Args: dst (str): The absolute path of the exported disk disk_type (str): The type of the image e.g template, file, empty... disk (dict): Disk attributes as found in workdir/current/virt/VM-NAME do_compress(bool): If true, apply compression to the exported disk. """ self.src = path.expandvars(disk['path']) self.name = path.basename(self.src) self.dst = path.join(path.expandvars(dst), self.name) self.dist_type = disk_type self.disk = disk self.exported_metadata = copy.deepcopy(disk['metadata']) self.do_compress = do_compress
def call(cmd, stdin=None, cwd=None): print(cmd) return subprocess.call([expandvars(cmd)], shell=True, stdin=stdin, cwd=cwd)
def __expand(self, path): path = path.replace("${MECHANIC_ROOT_DIR}", self.mechanicRootDir) path = expanduser(path) path = expandvars(path) return path
def handle(self, **options): if options["filename"]: fileobj = open(expanduser(expandvars(options["filename"])), "w") else: fileobj = self.stdout fileobj = write_nexus( fileobj, options["language_list"], options["meaning_list"], set(["L", "X"]), # exclude options["dialect"], # dialect True, # label cognate sets options["ascertainment_marker"])['fileobj'] fileobj.close()
def check_output(cmd, stdin=None, cwd=None): print(cmd) return subprocess.check_output([expandvars(cmd)], shell=True, stdin=stdin, cwd=cwd)
def load_AA_matrix(matrix_path): """ Load the amino acids descriptors. Return the list of amino acids and a matrix where each row are the descriptors of an amino acid. matrix_path -- Path to the file containing the amino acids descriptors. See the amino_acid_matrix folder for the file format. """ # Read the file f = open(path.expandvars(matrix_path), 'r') lines = f.readlines() f.close() amino_acids = [] nb_descriptor = len(lines[0].split()) - 1 aa_descriptors = np.zeros((len(lines), nb_descriptor)) # Read descriptors for i in xrange(len(lines)): s = lines[i].split() aa_descriptors[i] = np.array([float(x) for x in s[1:]]) amino_acids.append(s[0]) # If nb_descriptor == 1, then all normalized aa_descriptors will be 1 if nb_descriptor > 1: # Normalize each amino acid feature vector for i in xrange(len(aa_descriptors)): aa_descriptors[i] /= np.sqrt(np.dot(aa_descriptors[i],aa_descriptors[i])) return amino_acids, aa_descriptors
def expandvars_in_property(value): result = expandvars(value) if '$' in result or '%' in result: abort('Property contains an undefined environment variable: ' + value) return result
def _expand_path(p): return osp.normpath(osp.abspath(osp.expandvars(osp.expanduser(p))))
def call(cmd, stdin=None, cwd=libbuild.REPO_ROOT): print(cmd) return subprocess.call([expandvars(cmd)], shell=True, stdin=stdin, cwd=cwd)
def test_args_ca_certi_path_from_config(self): cli_args = argparse.Namespace(cacert=None, debug=False, format=None, insecure=False, reverse=False, duration=None, state=None, value=None) config_args = self.config['test7']['arguments'] arguments = get_arguments(cli_args, config_args, self.choices) # Arguments 'cacert' and 'insecure' is given in config. # Since insecure is False, ssl_verify should have CA Certificate path cacert_value = self.config['test7']['arguments'].get('cacert') ssl_result = arguments.get('ssl_verify') == \ expanduser(expandvars(cacert_value)) self.assertTrue(ssl_result)
def get_file_by_pattern(pattern, all=False): """Returns the first log whose path matches 'pattern', if all is True returns all logs that matches.""" if not pattern: return [] #debug('get_file_by_filename: searching for %s.' %pattern) # do envvar expandsion and check file file = path.expanduser(pattern) file = path.expandvars(file) if path.isfile(file): return [file] # lets see if there's a matching log global home_dir file = path.join(home_dir, pattern) if path.isfile(file): return [file] else: from fnmatch import fnmatch file = [] file_list = dir_list(home_dir) n = len(home_dir) for log in file_list: basename = log[n:] if fnmatch(basename, pattern): file.append(log) #debug('get_file_by_filename: got %s.' %file) if not all and file: file.sort() return [ file[-1] ] return file
def check_output(cmd, stdin=None, cwd=libbuild.REPO_ROOT): print(cmd) return subprocess.check_output([expandvars(cmd)], shell=True, stdin=stdin, cwd=cwd)
def get_conf(conf_item = "all"): """ Return configuration information by specific configuration Item conf_item: all, rest, todo """ user_conf_file = path.expandvars('$HOME') + "/.kreminder/config/kreminder.conf" global_conf_file = "/etc/kreminder.conf" if path.exists(user_conf_file) and path.isfile(user_conf_file): fp = open(user_conf_file, "r") elif path.exists(global_conf_file) and path.isfile(global_conf_file): fp = open(global_conf_file, "r") else: log("????????.", "error") return None all_conf = parse_conf_file(fp) if not cmp(conf_item, "all"): return all_conf elif not cmp(conf_item, "rest"): return all_conf[0] elif not cmp(conf_item, "todo"): return all_conf[1] else: log("?????%s?????." % conf_item, "warn") return None # Script starts from here
def dump_json(self): s = self.read_input( _("Save playlist to [{}]: ").format(self.json_file)) self.json_file = abspath(expanduser(expandvars(s or self.json_file))) try: makedirs(dirname(self.json_file), exist_ok=True) except: errmsg = _("'{}': Can't open file for writing").format( self.json_file) self.print_msg(errmsg, error=True) else: with open(self.json_file, 'w') as f: json.dump(self.entries, f, ensure_ascii=False, indent=2, sort_keys=True) self.print_msg(_("'{}' written").format(self.json_file))
def test_expandpath(): eq_(expandpath("some", False), expanduser('some')) eq_(expandpath("some", False), expandvars('some')) assert_true(isabs(expandpath('some'))) # this may have to go because of platform issues eq_(expandpath("$HOME"), expanduser('~'))
def expandpath(path, force_absolute=True): """Expand all variables and user handles in a path. By default return an absolute path """ path = expandvars(expanduser(path)) if force_absolute: path = abspath(path) return path
def __init__( self, disks, dst, compress, with_threads=True, *args, **kwargs ): self._disks = disks self._dst = os.path.expandvars(os.path.realpath(dst)) self._compress = compress self._with_threads = with_threads self._args = args self._kwargs = kwargs
def collect_paths(self): """ Returns: (list of str): The path of the disks that will be exported. """ return [os.path.expandvars(disk['path']) for disk in self._collect()]
def get_st_data_path(): return path.expandvars(platform_data_paths[platform.system()])
def __init__(self,shelldirname="",data_type="",filenum=""): # If no rundir specified if len(shelldirname) == 0: # Start init prompt shelldirname = raw_input('Please enter the rundir: ') self.rundir = opexp(shelldirname) # If Git version of the code AND filenum not given if len(filenum) == 0: self.filenum=raw_input("Please enter the file number to load (e.g. 000): ") else: self.filenum=filenum # If data type not specified if len(data_type) == 0: self.data_type=raw_input("Data Type? [(b)yte/ double (bb)yte/ (f)our byte/ (d)ouble precision] ") else: self.data_type = data_type # Parameters to load self.params=['pex','pey','pez','nx','ny','nz','lx','ly','lz',\ 'n_movieout','dt','T_i','T_e','n_0','b0x','b0y','b0z','m_e'] # Read parameters from file for i in self.params: comm="awk '/^#define/ && / "+i+" / {print $3}' "+self.rundir+"/paramfile" if syscomout("grep "+i+" "+self.rundir+"/paramfile")[0] == 0: exec('self.'+i+'=float(syscomout(comm)[1])') else: exec('self.'+i+'=float(0.)') self.dtmovie=self.n_movieout*self.dt # Derive some others self.nx=int(self.pex*self.nx); self.ny=int(self.pey*self.ny); self.nz=int(self.pez*self.nz) self.dx=self.lx/self.nx; self.dy=self.ly/self.ny; self.dz=self.lz/self.nz self.xx=np.linspace(0.,self.lx,self.nx); self.yy=np.linspace(0.,self.ly,self.ny); self.zz=np.linspace(0.,self.lz,self.nz) self.xxt=np.linspace(0.,2*np.pi,self.nx); self.yyt=np.linspace(0.,2*np.pi,self.ny); self.zzt=np.linspace(0.,2*np.pi,self.nz) self.B0 =np.sqrt(self.b0x**2+self.b0y**2+self.b0z**2) self.betai = 2*self.n_0*self.T_i/self.B0 self.betae = 2*self.n_0*self.T_e/self.B0 self.nprocs = int(self.pex*self.pey*self.pez) # If byte or double byte data, open the log file. if self.data_type in ("b", "bb"): print self.rundir+'/staging/movie.log.'+self.filenum self.logfile=open(self.rundir+"/staging/movie.log."+self.filenum,"r") self.logvars=['rho', 'jx', 'jy', 'jz', 'bx', 'by', 'bz', 'ex', 'ey'\ , 'ez', 'ne', 'jex', 'jey', 'jez', 'pexx', 'peyy', 'pezz', 'pexy', \ 'peyz', 'pexz', 'ni', 'jix', 'jiy', 'jiz', 'pixx', 'piyy', 'pizz', \ 'pixy', 'piyz', 'pixz'] self.szl=np.size(self.logvars) #### #### Method to print the parameters associated with the run ####
def __init__(self,shelldirname="",data_type=""): # If no rundir specified if len(shelldirname) == 0: # Start init prompt shelldirname = raw_input('Please enter the rundir: ') self.rundir = opexp(shelldirname) # If data type not specified if len(data_type) == 0: self.data_type=raw_input("Data Type? [(b)yte/ (d)ouble precision] ") else: self.data_type = data_type # Parameters to load self.readparams=['Nx0_tot', 'Ny0_tot', 'Nz0_tot', 'ALX_TOT', 'ALY_TOT',\ 'ALZ_TOT', 'DTP', 'NOUTMOV', 'NPTS', 'SD', 'TEMPF','BX0','BY0','BZ0',\ 'DENLOBE'] self.params=['nx', 'ny', 'nz', 'lx', 'ly', 'lz', 'dt', 'NOUTMOV', \ 'npts', 'SD', 'Temp','b0x','b0y','b0z','n_0'] # Read parameters from file for i in range(len(self.readparams)): comm="awk '/^ "+self.readparams[i]+" / {print $3}' "+self.rundir+"/paramfile" if syscomout(comm)[1].endswith(','): print self.params[i], '=', float(syscomout(comm)[1][:-1]) else: print self.params[i], '=', float(syscomout(comm)[1]) if syscomout("grep "+self.readparams[i]+" "+self.rundir+"/paramfile")[0] == 0: if syscomout(comm)[1].endswith(','): exec('self.'+self.params[i]+'=float(syscomout(comm)[1][:-1])') else: exec('self.'+self.params[i]+'=float(syscomout(comm)[1])') else: exec('self.'+self.params[i]+'=float(0.)') # Derive some others self.nx=int(self.nx) self.ny=int(self.ny) self.nz=int(self.nz) self.dx=self.lx/self.nx; self.dy=self.ly/self.ny; self.dz=self.lz/self.nz self.xx=np.linspace(0.,self.lx,self.nx); self.yy=np.linspace(0.,self.ly,self.ny); self.zz=np.linspace(0.,self.lz,self.nz) self.xxt=np.linspace(0.,2*pi,self.nx); self.yyt=np.linspace(0.,2*pi,self.ny); self.zzt=np.linspace(0.,2*pi,self.nz) self.beta = 2*self.n_0*self.Temp/(self.b0x**2+self.b0y**2+self.b0z**2) #### #### Method to print the parameters associated with the run ####