我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.path.sep()。
def api_get_spec(context, method_list): '''Generates and Returns the spec file data :param context: Dictionary with app, session, version and api fields :type: ```dict
:param method_list: List of API methods to call :type: ```list``` :return: generated spec file :rtype: ```basestring``` ''' _generate_documentation(context, method_list) with open(tempfile.gettempdir() + op.sep + 'spec.yaml') as stream: try: spec_file = yaml.load(stream) except yaml.YAMLError as ex: raise Exception("Please try again. Exception: {}".format(ex)) return json.dumps(spec_file)
```
def write_temp(self): ''' Stores changes to the spec in a temp file. ''' spec = { "swagger": self.api.__getattribute__('swagger'), "info": self.api.__getattribute__('info'), "host": self.api.__getattribute__('host'), "schemes": self.api.__getattribute__('schemes'), "consumes": self.api.__getattribute__('consumes'), "produces": self.api.__getattribute__('produces'), "paths": self.api.__getattribute__('paths'), "definitions": self.api.__getattribute__('definitions') } stream = file((tempfile.gettempdir() + op.sep + 'temp.yaml'), 'w') for x in self.order: yaml.dump({x: spec[x]}, stream, default_flow_style=False)
def update_spec(self): ''' Updates the specification from the temp file. ''' try: os.rename( tempfile.gettempdir() + op.sep + 'temp.yaml', tempfile.gettempdir() + op.sep + 'spec.yaml') except Exception as e: raise Exception( "Spec file not found, please try again." " Exception: {}".format(e))
def list_templates(self): found = set() for searchpath in self.searchpath: walk_dir = os.walk(searchpath, followlinks=self.followlinks) for dirpath, dirnames, filenames in walk_dir: for filename in filenames: template = os.path.join(dirpath, filename) \ [len(searchpath):].strip(os.path.sep) \ .replace(os.path.sep, '/') if template[:2] == './': template = template[2:] if template not in found: found.add(template) return sorted(found)
def proc(tsk): env = tsk.env gen = tsk.generator inc_nodes = gen.to_incnodes(Utils.to_list(getattr(gen,'includes',[])) + env['INCLUDES']) # FIXME the if-else construct will not work in python 2 cmd = ( [env.PROC] + ['SQLCHECK=SEMANTICS'] + (['SYS_INCLUDE=(' + ','.join(env.PROC_INCLUDES) + ')'] if env.PROC_INCLUDES else []) + ['INCLUDE=(' + ','.join( [i.bldpath() for i in inc_nodes] ) + ')'] + ['userid=' + env.PROC_CONNECTION] + ['INAME=' + tsk.inputs[0].bldpath()] + ['ONAME=' + tsk.outputs[0].bldpath()] ) exec_env = { 'ORACLE_HOME': env.PROC_ORACLE, 'LD_LIBRARY_PATH': env.PROC_ORACLE + path.sep + 'lib', } if env.PROC_TNS_ADMIN: exec_env['TNS_ADMIN'] = env.PROC_TNS_ADMIN return tsk.exec_command(cmd, env=exec_env)
def list_examples(self): if isdir(self.examples_dir): # examples = sorted(os.listdir(self.examples_dir)) examples = [dirname(y).replace(self.examples_dir + sep, '') for x in os.walk(self.examples_dir) for y in glob.glob(util.safe_join(x[0], 'info'))] click.secho('') for example in examples: example_dir = util.safe_join(self.examples_dir, example) if isdir(example_dir): info_path = util.safe_join(example_dir, 'info') info = '' if isfile(info_path): with codecs.open(info_path, 'r', 'utf-8') as info_file: info = info_file.read().replace('\n', '') click.secho(' ' + example, fg='blue', bold=True) click.secho('-' * click.get_terminal_size()[0]) click.secho(' ' + info) click.secho('') click.secho(EXAMPLE_DIR_FILE, fg='green') click.secho(EXAMPLE_OF_USE_CAD, fg='green') else: util._check_package('examples') return 1 return 0
def probably_a_local_import(self, imp_name): """ Like the corresponding method in the base class, but this also supports Cython modules. """ if imp_name.startswith(u"."): # Relative imports are certainly not local imports. return False imp_name = imp_name.split(u".", 1)[0] base_path = dirname(self.filename) base_path = join(base_path, imp_name) # If there is no __init__.py next to the file its not in a package # so can't be a relative import. if not exists(join(dirname(base_path), "__init__.py")): return False for ext in [".py", sep, ".pyc", ".so", ".sl", ".pyd", ".pyx"]: if exists(base_path + ext): return True return False
def walk_directories(root): """'find' in a generator function.""" for child in os.listdir(root): if child.startswith("."): continue full_path = path.join(root, child) if path.isfile(full_path): yield full_path elif full_path.endswith((path.sep+".", path.sep+"..")): continue elif path.islink(full_path): continue else: for fp in walk_directories(full_path): yield fp
def main(): args = parseArgs() toIgnore = set(args.toIgnore) while True: try: item = SlurpItem.readIn() ignoredDir = False for directory in item.path.split(sep): if directory in toIgnore: ignoredDir = True break if not ignoredDir: item.print() except(EOFError): break
def getFilesInDir(self, excludePath=None): ''' Recursively returns all files under a given directory. ''' path = self._dir if not path.endswith(pathSeparator): path = path + pathSeparator files = [path] for file in iglob(path + '**' + pathSeparator + '*', recursive=True): if excludePath is not None and file.startswith(excludePath): continue files.append(file) return files
def _find_new_data_files(root, timestamp, ignoredirs=[".smt", ".hg", ".svn", ".git", ".bzr"], ignore_extensions=[".pyc"]): """Finds newly created/changed files in root.""" length_root = len(root) + len(path.sep) new_files = [] for root, dirs, files in os.walk(root): for igdir in ignoredirs: if igdir in dirs: dirs.remove(igdir) for file in files: if path.splitext(file)[1] not in ignore_extensions: full_path = path.join(root, file) relative_path = path.join(root[length_root:], file) last_modified = datetime.fromtimestamp(os.stat(full_path).st_mtime) if last_modified >= timestamp: new_files.append(relative_path) return new_files
def doc2path(self, docname, base=True, suffix=None): """Return the filename for the document name. If *base* is True, return absolute path under self.srcdir. If *base* is None, return relative path to self.srcdir. If *base* is a path string, return absolute path under that. If *suffix* is not None, add it instead of config.source_suffix. """ docname = docname.replace(SEP, path.sep) if suffix is None: for candidate_suffix in self.config.source_suffix: if path.isfile(path.join(self.srcdir, docname) + candidate_suffix): suffix = candidate_suffix break else: # document does not exist suffix = self.config.source_suffix[0] if base is True: return path.join(self.srcdir, docname) + suffix elif base is None: return docname + suffix else: return path.join(base, docname) + suffix
def relfn2path(self, filename, docname=None): """Return paths to a file referenced from a document, relative to documentation root and absolute. In the input "filename", absolute filenames are taken as relative to the source dir, while relative filenames are relative to the dir of the containing document. """ if filename.startswith('/') or filename.startswith(os.sep): rel_fn = filename[1:] else: docdir = path.dirname(self.doc2path(docname or self.docname, base=None)) rel_fn = path.join(docdir, filename) try: # the path.abspath() might seem redundant, but otherwise artifacts # such as ".." will remain in the path return rel_fn, path.abspath(path.join(self.srcdir, rel_fn)) except UnicodeDecodeError: # the source directory is a bytestring with non-ASCII characters; # let's try to encode the rel_fn in the file system encoding enc_rel_fn = rel_fn.encode(sys.getfilesystemencoding()) return rel_fn, path.abspath(path.join(self.srcdir, enc_rel_fn))
def background_render(self, context, cls, preset): generator = path.dirname(path.realpath(__file__)) + path.sep + "archipack_thumbs.py" addon_name = __name__.split('.')[0] matlib_path = context.user_preferences.addons[addon_name].preferences.matlib_path # Run external instance of blender like the original thumbnail generator. cmd = [ bpy.app.binary_path, "--background", "--factory-startup", "-noaudio", "--python", generator, "--", "addon:" + addon_name, "matlib:" + matlib_path, "cls:" + cls, "preset:" + preset ] popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True) for stdout_line in iter(popen.stdout.readline, ""): yield stdout_line popen.stdout.close() popen.wait()
def scan_files(self, category): file_list = [] # load default presets dir_path = path.dirname(path.realpath(__file__)) sub_path = "presets" + path.sep + category presets_path = path.join(dir_path, sub_path) if path.exists(presets_path): file_list += [presets_path + path.sep + f[:-3] for f in listdir(presets_path) if f.endswith('.py') and not f.startswith('.')] # load user def presets preset_paths = bpy.utils.script_paths("presets") for preset in preset_paths: presets_path = path.join(preset, category) if path.exists(presets_path): file_list += [presets_path + path.sep + f[:-3] for f in listdir(presets_path) if f.endswith('.py') and not f.startswith('.')] file_list.sort() return file_list
def files(self): """A generator function for iterating over the individual files of the FileSet. The generator yields a tuple of ``(rel_dir_name, file_name)``: 1. *rel_dir_name*: The path relative to the starting directory 2. *file_name*: The unqualified file name """ directory = self.get_directory() prefix = len(directory) + (0 if is_root(directory) else 1) include = None exclude = None for root, dirs, files in self.walk(directory): # Remove the constant part of the path inluding the first path sep rel_dir_name = root[prefix:] matched, include, exclude = self._receive(directory, rel_dir_name, dirs, files, include, exclude) for file_name in matched: yield rel_dir_name, file_name
def _filter_selection(self, folders=True, files=True): """Filter the list of selected objects :param folders: if True - folders will be included in selection :param files: if True - files will be included in selection """ if folders and files: return t = [] for entry in self.selection: if entry == '..' + path.sep: pass elif folders and self.browser.file_system.is_dir(entry): t.append(entry) elif files and not self.browser.file_system.is_dir(entry): t.append(entry) self.selection = t
def splitstrip(string, sep=','): """return a list of stripped string by splitting the string given as argument on `sep` (',' by default). Empty string are discarded. >>> splitstrip('a, b, c , 4,,') ['a', 'b', 'c', '4'] >>> splitstrip('a') ['a'] >>> :type string: str or unicode :param string: a csv line :type sep: str or unicode :param sep: field separator, default to the comma (',') :rtype: str or unicode :return: the unquoted string (or the input string if it wasn't quoted) """ return [word.strip() for word in string.split(sep) if word.strip()]
def meta_autodetect_platform(cls): """ Dark magic to autodetect the platform for built-in shellcodes. User-defined shellcodes must define *arch* and *os*. """ abspath = path.abspath join = path.join split = path.split splitext = path.splitext sep = path.sep module = cls.__module__ if module != '__main__': tokens = cls.__module__.split('.') if len(tokens) < 2 or tokens[0] != base_package or \ tokens[1] == base_file: return tokens.insert(-1, 'any') tokens = tokens[1:3] else: module = abspath(sys.modules[module].__file__) if not module.startswith(base_dir): return tokens = module.split(sep) tokens = tokens[len(base_dir.split(sep)):-1] while len(tokens) < 2: tokens.append('any') cls.arch, cls.os = tokens
def probably_a_local_import(self, imp_name): if imp_name.startswith(u"."): # Relative imports are certainly not local imports. return False imp_name = imp_name.split(u".", 1)[0] base_path = dirname(self.filename) base_path = join(base_path, imp_name) # If there is no __init__.py next to the file its not in a package # so can't be a relative import. if not exists(join(dirname(base_path), "__init__.py")): return False for ext in [".py", sep, ".pyc", ".so", ".sl", ".pyd"]: if exists(base_path + ext): return True return False
def split_template_path(template): """Split a path into segments and perform a sanity check. If it detects '..' in the path it will raise a `TemplateNotFound` error. """ pieces = [] for piece in template.split('/'): if path.sep in piece \ or (path.altsep and path.altsep in piece) or \ piece == path.pardir: raise TemplateNotFound(template) elif piece and piece != '.': pieces.append(piece) return pieces
def configure(cnf): env = cnf.env if not env.PROC_ORACLE: env.PROC_ORACLE = cnf.options.oracle_home if not env.PROC_TNS_ADMIN: env.PROC_TNS_ADMIN = cnf.options.tns_admin if not env.PROC_CONNECTION: env.PROC_CONNECTION = cnf.options.connection cnf.find_program('proc', var='PROC', path_list=env.PROC_ORACLE + path.sep + 'bin')
def safe_join(base, *paths): """ Joins one or more path components to the base path component intelligently. Returns a normalized, absolute version of the final path. The final path must be located inside of the base path component (otherwise a ValueError is raised). """ base = force_text(base) paths = [force_text(p) for p in paths] final_path = abspathu(join(base, *paths)) base_path = abspathu(base) # Ensure final_path starts with base_path (using normcase to ensure we # don't false-negative on case insensitive operating systems like Windows), # further, one of the following conditions must be true: # a) The next character is the path separator (to prevent conditions like # safe_join("/dir", "/../d")) # b) The final path must be the same as the base path. # c) The base path must be the most root path (meaning either "/" or "C:\\") if (not normcase(final_path).startswith(normcase(base_path + sep)) and normcase(final_path) != normcase(base_path) and dirname(normcase(base_path)) != normcase(base_path)): raise SuspiciousFileOperation( 'The joined path ({}) is located outside of the base path ' 'component ({})'.format(final_path, base_path)) return final_path
def makedir(self, name): """ return a directory path object with the given name. If the directory does not yet exist, it will be created. You can use it to manage files likes e. g. store/retrieve database dumps across test sessions. :param name: must be a string not containing a ``/`` separator. Make sure the name contains your plugin or application identifiers to prevent clashes with other cache users. """ if _sep in name or _altsep is not None and _altsep in name: raise ValueError("name is not allowed to contain path separators") return self._cachedir.ensure_dir("d", name)
def test_1(self): n = lambda path: path.replace('/', sep) assert_equal(minrelpath(n('aa/bb')), n('aa/bb')) assert_equal(minrelpath('..'), '..') assert_equal(minrelpath(n('aa/..')), '') assert_equal(minrelpath(n('aa/../bb')), 'bb') assert_equal(minrelpath(n('aa/bb/..')), 'aa') assert_equal(minrelpath(n('aa/bb/../..')), '') assert_equal(minrelpath(n('aa/bb/../cc/../dd')), n('aa/dd')) assert_equal(minrelpath(n('.././..')), n('../..')) assert_equal(minrelpath(n('aa/bb/.././../dd')), n('dd'))