我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.path.normpath()。
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) else: 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 = self.download(template) else: 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))
def rev_parse_manifest_path(self, cwd): """ Search parent directories for package.json. Starting at the current working directory. Go up one directory at a time checking if that directory contains a package.json file. If it does, return that directory. """ name = 'package.json' manifest_path = path.normpath(path.join(cwd, name)) bin_path = path.join(cwd, 'node_modules/.bin/') if path.isfile(manifest_path) and path.isdir(bin_path): return manifest_path parent = path.normpath(path.join(cwd, '../')) if parent == '/' or parent == cwd: return None return self.rev_parse_manifest_path(parent)
def find_local_cmd_path(self, cmd): """ Find a local binary in node_modules/.bin. Given package.json filepath and a local binary to find, look in node_modules/.bin for that binary. """ cwd = path.dirname(self.manifest_path) binary = self.get_pkg_bin_cmd(cmd) if binary: return path.normpath(path.join(cwd, binary)) return self.find_ancestor_cmd_path(cmd, cwd)
def find_ancestor_cmd_path(self, cmd, cwd): """Recursively check for command binary in ancestors' node_modules/.bin directories.""" node_modules_bin = path.normpath(path.join(cwd, 'node_modules/.bin/')) binary = path.join(node_modules_bin, cmd) if sublime.platform() == 'windows' and path.splitext(binary)[1] != '.cmd': binary += '.cmd' if binary and access(binary, X_OK): return binary parent = path.normpath(path.join(cwd, '../')) if parent == '/' or parent == cwd: return None return self.find_ancestor_cmd_path(cmd, parent)
def fix_scheme_in_settings(settings_file,current_scheme, new_scheme, regenerate=False): """Change the color scheme in the given Settings to a background-corrected one""" from os.path import join, normpath, isfile settings = load_settings(settings_file) settings_scheme = settings.get("color_scheme") if current_scheme == settings_scheme: new_scheme_path = join(packages_path(), normpath(new_scheme[len("Packages/"):])) if isfile(new_scheme_path) and not regenerate: settings.set("color_scheme", new_scheme) else: generate_scheme_fix(current_scheme, new_scheme_path) settings.set("color_scheme", new_scheme) save_settings(settings_file) return True return False
def __init__(self, scheme_file, color_filter=None): """Initialize.""" if color_filter is None: color_filter = self.filter self.color_scheme = path.normpath(scheme_file) self.scheme_file = path.basename(self.color_scheme) self.plist_file = color_filter( readPlistFromBytes( re.sub( br"^[\r\n\s]*<!--[\s\S]*?-->[\s\r\n]*|<!--[\s\S]*?-->", b'', sublime.load_binary_resource(sublime_format_path(self.color_scheme)) ) ) ) self.scheme_file = scheme_file self.matched = {} self.parse_scheme()
def is_subdir(path, directory): """ Returns true if *path* in a subdirectory of *directory*. Both paths must be absolute. :arg path: An absolute path. :type path: string or bytes """ from os.path import normpath, normcase, sep path = normpath(normcase(path)) directory = normpath(normcase(directory)) if len(path) > len(directory): sep = sep.encode('ascii') if isinstance(directory, bytes) else sep if path.startswith(directory.rstrip(sep) + sep): return True return False
def reduce_dirs(dirs): """ Given a sequence of directories, remove duplicates and any directories nested in one of the other paths. (Useful for recursive path searching). :arg dirs: Sequence of directory paths. :type dirs: sequence :return: A unique list of paths. :rtype: list """ dirs = list({_os.path.normpath(_os.path.abspath(d)) for d in dirs}) dirs.sort(key=lambda d: len(d)) for i in range(len(dirs) - 1, -1, -1): for j in range(i): print(i, j) if len(dirs[i]) == len(dirs[j]): break elif is_subdir(dirs[i], dirs[j]): del dirs[i] break return dirs
def config_win(): try: import winreg as reg key = reg.CreateKey(reg.HKEY_CURRENT_USER, 'SOFTWARE\\Classes\\nzblnk') reg.SetValue(key, '', reg.REG_SZ, 'URL:nzblnk') reg.SetValueEx(key, 'URL Protocol', 0, reg.REG_SZ, '') reg.CloseKey(key) key = reg.CreateKey(reg.HKEY_CURRENT_USER, 'SOFTWARE\\Classes\\nzblnk\\shell\\open\\command') reg.SetValue(key, '', reg.REG_SZ, '"{0}" "%1"'.format(op.normpath(os.path.abspath(sys.executable)))) reg.CloseKey(key) except (OSError, ImportError): print(Col.FAIL + ' FAILED to setup registry link for NZBLNK scheme!' + Col.OFF) sleep(wait_time) sys.exit(2)
def _get_config_path(self, config_level): # we do not support an absolute path of the gitconfig on windows , # use the global config instead if is_win and config_level == "system": config_level = "global" if config_level == "system": return "/etc/gitconfig" elif config_level == "user": config_home = os.environ.get("XDG_CONFIG_HOME") or osp.join(os.environ.get("HOME", '~'), ".config") return osp.normpath(osp.expanduser(osp.join(config_home, "git", "config"))) elif config_level == "global": return osp.normpath(osp.expanduser("~/.gitconfig")) elif config_level == "repository": return osp.normpath(osp.join(self.git_dir, "config")) raise ValueError("Invalid configuration level: %r" % config_level)
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('\\', '/')
def obfuscate_path(file_path): """Create an obfuscated path name. Parameters ---------- file_path : str Returns ------- obfuscated path : str """ from logic.identifier import get_obfuscated_name obf_path = [get_obfuscated_name(p) for p in normpath(file_path).split(sep)] if obf_path[-1][-3:] in ['.py', '.kv']: obf_path[-1] = ''.join([get_obfuscated_name(obf_path[-1][:-3]), obf_path[-1][-3:]]) return join(*obf_path)
def main(): args = check_argv() # Complete options options_dict = default_options_dict.copy() options_dict["data_dir"] = path.normpath(args.data_dir) options_dict["model_dir"] = path.join(MODEL_DIR, options_dict["data_dir"].replace("data" + os.sep, "")) options_dict["init_am_n_iter"] = args.init_am_n_iter options_dict["segment_n_iter"] = args.segment_n_iter options_dict["K_max"] = args.K_max options_dict["min_duration"] = args.min_duration options_dict["n_slices_max"] = args.n_slices_max options_dict["p_boundary_init"] = args.p_boundary_init options_dict["n_cpus"] = args.n_cpus options_dict["n_batches"] = args.n_batches ksegment(options_dict)
def test_module_imports_are_direct(): my_filename = abspath(inspect.getfile(inspect.currentframe())) my_dirname = dirname(my_filename) diagnose_imports_filename = join(my_dirname, 'diagnose_imports.py') diagnose_imports_filename = normpath(diagnose_imports_filename) process = subprocess.Popen( [ sys.executable, normpath(diagnose_imports_filename), '--problems', '--by-importer' ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=-1) output, _ = process.communicate() assert output == '', "There are import problems:\n" + output.decode()
def suite(package): """Assemble test suite for doctests in path (recursively)""" from importlib import import_module for module in find_modules(package.__file__): try: module = import_module(module) yield DocTestSuite(module, globs=Context(module.__dict__.copy()), optionflags=ELLIPSIS | NORMALIZE_WHITESPACE) except ValueError: pass # No doctests in module except ImportError: import warnings warnings.warn('Unimportable module: {}'.format(module)) # Add documentation tests yield DocFileSuite(path.normpath(path.join(path.dirname(__file__), '..', '..', '..', 'doc', 'scripting.rst')), module_relative=False, globs=Context(module.__dict__.copy()), optionflags=ELLIPSIS | NORMALIZE_WHITESPACE )
def __init__(self, senna_path, operations, encoding='utf-8'): self._encoding = encoding self._path = path.normpath(senna_path) + sep # Verifies the existence of the executable on the self._path first #senna_binary_file_1 = self.executable(self._path) exe_file_1 = self.executable(self._path) if not path.isfile(exe_file_1): # Check for the system environment if 'SENNA' in environ: #self._path = path.join(environ['SENNA'],'') self._path = path.normpath(environ['SENNA']) + sep exe_file_2 = self.executable(self._path) if not path.isfile(exe_file_2): raise OSError("Senna executable expected at %s or %s but not found" % (exe_file_1,exe_file_2)) self.operations = operations
def start_listening(host_ip=DEFAULT_IP, host_port=DEFAULT_PORT, proc_num=DEFAULT_PROCS): global config from os.path import isfile path = normpath(abspath(dirname(__file__))) config_path = join(path, 'config.json') if isfile(config_path): with open(config_path, 'r') as cfg: config = loads(cfg.read()) else: config = {} sentry = Sentry(application) logging.getLogger(__name__).info( 'Start Listening on {}:{} with {} procs'.format( host_ip, host_port, proc_num ) ) global pool pool = Pool(processes=proc_num, initializer=init_worker) try: application.run(debug=False, host=host_ip, port=host_port) finally: pool.terminate() pool.close()
def get_matching_files(dirname, exclude_matchers=()): """Get all file names in a directory, recursively. Exclude files and dirs matching some matcher in *exclude_matchers*. """ # dirname is a normalized absolute path. dirname = path.normpath(path.abspath(dirname)) dirlen = len(dirname) + 1 # exclude final os.path.sep for root, dirs, files in walk(dirname, followlinks=True): relativeroot = root[dirlen:] qdirs = enumerate(path_stabilize(path.join(relativeroot, dn)) for dn in dirs) qfiles = enumerate(path_stabilize(path.join(relativeroot, fn)) for fn in files) for matcher in exclude_matchers: qdirs = [entry for entry in qdirs if not matcher(entry[1])] qfiles = [entry for entry in qfiles if not matcher(entry[1])] dirs[:] = sorted(dirs[i] for (i, _) in qdirs) for i, filename in sorted(qfiles): yield filename
def read_config(): self_path = os.path.abspath(os.path.dirname(__file__)) ml_cmp_conf = os.path.join(self_path,'ml_cmp.conf') if os.path.isfile(ml_cmp_conf): with open(ml_cmp_conf, 'r') as f: cfg = f.read() try: cfg = json.loads(cfg) except ValueError: raise ValueError('Invalid ml_cmp.conf: %s' % ml_cmp_conf) # check settings missing = set(('node', 'rapydscript', 'rs_options')) - set(cfg.keys()) if missing: raise ValueError('Missing settings in ml_cmp.conf: %s' % missing) ret = [ [ os.path.normpath(cfg['node']), os.path.normpath(cfg['rapydscript']) ], cfg['rs_options'], cfg.get('ugly_template', False) ] return ret
def make_pyj_js(rs_s, dest_base_fname): """ produce 2 files - dest_base_fname.pyj - dest_base_fname.js rs_s - RapydScript string dest_base_fname - 'd:/dfsdf/sdfsdf/out_name' - no ext! """ from os import path pyj_fname = path.normpath( dest_base_fname+'.pyj') js_fname = path.normpath(dest_base_fname+'.js') with open(pyj_fname, 'w') as file_pyj: file_pyj.write(rs_s) #cmd = RapydRS_cmd cmd_lst = RS_CMD + [pyj_fname] + RS_OPT + ['-o', js_fname] #compile pyj to js result = Popen(cmd_lst, stdout = PIPE, stderr = PIPE, shell = True).communicate() if result[1]: raise ShellError("'%s' triggered the following OS error: %s" % ('make_pyj_js', result[1]))
def save_visualization(algo_result, metric_vis, metric, scene, tgt_dir): fig = init_figure() # algorithm result as background plt.imshow(algo_result, **settings.disp_map_args(scene, cmap="gray")) # metric visualization on top if scene.hidden_gt() and metric.pixelize_results() and settings.PIXELIZE: metric_vis = plotting.pixelize(metric_vis, noise_factor=0.05) cm = plt.imshow(metric_vis, **settings.metric_args(metric)) add_colorbar(cm, metric.colorbar_bins) # save fig relative_fname = get_relative_path(scene, metric.get_id()) fpath = op.normpath(op.join(tgt_dir, relative_fname)) plotting.save_tight_figure(fig, fpath, hide_frames=True, pad_inches=0.01) return relative_fname
def get_appname_from_path(absolute_path): absolute_path = op.normpath(absolute_path) parts = absolute_path.split(os.path.sep) parts.reverse() for key in ("apps", "slave-apps", "master-apps"): try: idx = parts.index(key) except ValueError: continue else: try: if parts[idx + 1] == "etc": return parts[idx - 1] except IndexError: pass continue #return None return "-"
def dir_from_output(output): """Get library directory based on the output of clang. Args: output (str): raw output from clang Returns: str: path to folder with libclang """ log.debug("real output: %s", output) if platform.system() == "Darwin": # [HACK] uh... I'm not sure why it happens like this... folder_to_search = path.join(output, '..', '..') log.debug("folder to search: %s", folder_to_search) return folder_to_search elif platform.system() == "Windows": log.debug("architecture: %s", platform.architecture()) return path.normpath(output) elif platform.system() == "Linux": return path.normpath(path.dirname(output)) return None
def test_persistence(self): """Test if compilation db is persistent.""" include_prefixes = ['-I'] db = CompilationDb(include_prefixes) expected_lib = [Flag('-Dlib_EXPORTS'), Flag('-fPIC')] expected_main = [Flag('-I' + path.normpath('/lib_include_dir'))] lib_file_path = path.normpath('/home/user/dummy_lib.cpp') main_file_path = path.normpath('/home/user/dummy_main.cpp') path_to_db = path.join(path.dirname(__file__), 'compilation_db_files', 'command') scope = SearchScope(from_folder=path_to_db) self.assertEqual(expected_lib, db.get_flags(lib_file_path, scope)) self.assertEqual(expected_main, db.get_flags(main_file_path, scope)) # check persistence self.assertGreater(len(db._cache), 2) self.assertEqual(path.join(path_to_db, "compile_commands.json"), db._cache[main_file_path]) self.assertEqual(path.join(path_to_db, "compile_commands.json"), db._cache[lib_file_path])
def test_get_c_flags(self): """Test argument filtering for c language.""" include_prefixes = ['-I'] db = CompilationDb(include_prefixes) main_file_path = path.normpath('/home/blah.c') # also try to test a header path_to_db = path.join(path.dirname(__file__), 'compilation_db_files', 'command_c') scope = SearchScope(from_folder=path_to_db) flags = db.get_flags(main_file_path, scope) self.assertNotIn(Flag('-c'), flags) self.assertNotIn(Flag('-o'), flags) self.assertIn(Flag('-Wno-poison-system-directories'), flags) self.assertIn(Flag('-march=armv7-a'), flags)
def _update_service_config(self, env, service_config): if isinstance(service_config, dict): dev_overrides = service_config.pop('dev_overrides', {}) if env == 'dev': service_config.update(dev_overrides) if 'volumes' in service_config: # Expand ~, ${HOME}, ${PWD}, etc. found in the volume src path updated_volumes = [] for volume in service_config['volumes']: vol_pieces = volume.split(':') vol_pieces[0] = path.normpath(path.expandvars(path.expanduser(vol_pieces[0]))) updated_volumes.append(':'.join(vol_pieces)) service_config['volumes'] = updated_volumes for engine_name in self.remove_engines: if engine_name in service_config: del service_config[engine_name]
def project_root(parser, projdir=os.getcwd()): """try to find project's root and add it to sys.path""" previousdir = curdir = osp.abspath(projdir) testercls = PyTester conf_file_path = osp.join(curdir, CONF_FILE) if osp.isfile(conf_file_path): testercls = load_pytest_conf(conf_file_path, parser) while this_is_a_testdir(curdir) or \ osp.isfile(osp.join(curdir, '__init__.py')): newdir = osp.normpath(osp.join(curdir, os.pardir)) if newdir == curdir: break previousdir = curdir curdir = newdir conf_file_path = osp.join(curdir, CONF_FILE) if osp.isfile(conf_file_path): testercls = load_pytest_conf(conf_file_path, parser) return previousdir, testercls
def load_django_settings(self, dirname): """try to find project's setting and load it""" curdir = osp.abspath(dirname) previousdir = curdir while not osp.isfile(osp.join(curdir, 'settings.py')) and \ osp.isfile(osp.join(curdir, '__init__.py')): newdir = osp.normpath(osp.join(curdir, os.pardir)) if newdir == curdir: raise AssertionError('could not find settings.py') previousdir = curdir curdir = newdir # late django initialization settings = load_module_from_modpath(modpath_from_file(osp.join(curdir, 'settings.py'))) from django.core.management import setup_environ setup_environ(settings) settings.DEBUG = False self.settings = settings # add settings dir to pythonpath since it's the project's root if curdir not in sys.path: sys.path.insert(1, curdir)