Python os.path 模块,rstrip() 实例源码
我们从Python开源项目中,提取了以下11个代码示例,用于说明如何使用os.path.rstrip()。
def findFileOrDirectory(self, path):
path = self.getFilePath(path)
if not path:
return None, None
xmlPath = self.simXml.getXmlPath(path)
node = self.simXml.find(xmlPath)
if node == None:
if path[-1] != "/":
#try to select direcotry
path += "/"
xmlPath = self.simXml.getXmlPath(path)
node = self.simXml.find(xmlPath)
else:
#try to select file
path = path.rstrip("/")
xmlPath = self.simXml.getXmlPath(path)
node = self.simXml.find(xmlPath)
if node == None:
logging.error("Failed to select: %s" %xmlPath)
return None, None
return node, xmlPath
def resolve_name(self, modname, parents, path, base):
if modname is None:
if path:
mod_cls = path.rstrip('.')
else:
mod_cls = None
# if documenting a class-level object without path,
# there must be a current class, either from a parent
# auto directive ...
mod_cls = self.env.temp_data.get('autodoc:class')
# ... or from a class directive
if mod_cls is None:
mod_cls = self.env.ref_context.get('py:class')
# ... if still None, there's no way to know
if mod_cls is None:
return None, []
modname, cls = rpartition(mod_cls, '.')
parents = [cls]
# if the module name is still missing, get it like above
if not modname:
modname = self.env.temp_data.get('autodoc:module')
if not modname:
modname = self.env.ref_context.get('py:module')
# ... else, it stays None, which means invalid
return modname, parents + [base]
def add_url_path_component(path, component):
return '%s/%s' % (path.rstrip('/'), component.lstrip('/'))
def parse_name(self):
"""Determine what module to import and what attribute to document.
Returns True and sets *self.modname*, *self.objpath*, *self.fullname*,
*self.args* and *self.retann* if parsing and resolving was successful.
"""
# first, parse the definition -- auto directives for classes and
# functions can contain a signature which is then used instead of
# an autogenerated one
try:
explicit_modname, path, base, args, retann = \
py_ext_sig_re.match(self.name).groups()
except AttributeError:
self.directive.warn('invalid signature for auto%s (%r)' %
(self.objtype, self.name))
return False
# support explicit module and class name separation via ::
if explicit_modname is not None:
modname = explicit_modname[:-2]
parents = path and path.rstrip('.').split('.') or []
else:
modname = None
parents = []
self.modname, self.objpath = \
self.resolve_name(modname, parents, path, base)
if not self.modname:
return False
self.args = args
self.retann = retann
self.fullname = (self.modname or '') + \
(self.objpath and '.' + '.'.join(self.objpath) or '')
return True
def resolve_name(self, modname, parents, path, base):
if modname is None:
if path:
modname = path.rstrip('.')
else:
# if documenting a toplevel object without explicit module,
# it can be contained in another auto directive ...
modname = self.env.temp_data.get('autodoc:module')
# ... or in the scope of a module directive
if not modname:
modname = self.env.ref_context.get('py:module')
# ... else, it stays None, which means invalid
return modname, parents + [base]
def parse_got_revision(gclient_output, got_revision_mapping):
"""Translate git gclient revision mapping to build properties."""
properties = {}
solutions_output = {
# Make sure path always ends with a single slash.
'%s/' % path.rstrip('/') : solution_output for path, solution_output
in gclient_output['solutions'].iteritems()
}
for dir_name, property_name in got_revision_mapping.iteritems():
# Make sure dir_name always ends with a single slash.
dir_name = '%s/' % dir_name.rstrip('/')
if dir_name not in solutions_output:
continue
solution_output = solutions_output[dir_name]
if solution_output.get('scm') is None:
# This is an ignored DEPS, so the output got_revision should be 'None'.
revision = commit_position = None
else:
# Since we are using .DEPS.git, everything had better be git.
assert solution_output.get('scm') == 'git'
revision = git('rev-parse', 'HEAD', cwd=dir_name).strip()
commit_position = get_commit_position(dir_name)
properties[property_name] = revision
if commit_position:
properties['%s_cp' % property_name] = commit_position
return properties
def parse_got_revision(gclient_output, got_revision_mapping):
"""Translate git gclient revision mapping to build properties."""
properties = {}
solutions_output = {
# Make sure path always ends with a single slash.
'%s/' % path.rstrip('/') : solution_output for path, solution_output
in gclient_output['solutions'].iteritems()
}
for dir_name, property_name in got_revision_mapping.iteritems():
# Make sure dir_name always ends with a single slash.
dir_name = '%s/' % dir_name.rstrip('/')
if dir_name not in solutions_output:
continue
solution_output = solutions_output[dir_name]
if solution_output.get('scm') is None:
# This is an ignored DEPS, so the output got_revision should be 'None'.
revision = commit_position = None
else:
# Since we are using .DEPS.git, everything had better be git.
assert solution_output.get('scm') == 'git'
revision = git('rev-parse', 'HEAD', cwd=dir_name).strip()
commit_position = get_commit_position(dir_name)
properties[property_name] = revision
if commit_position:
properties['%s_cp' % property_name] = commit_position
return properties
def _canonicalize_path(path):
import svn.core
try:
return svn.core.svn_path_canonicalize(path)
except AttributeError: # svn_path_canonicalize() appeared in 1.4.0 bindings
# There's so much more that we *could* do here, but if we're
# here at all its because there's a really old Subversion in
# place, and those older Subversion versions cared quite a bit
# less about the specifics of path canonicalization.
if re.search(_re_url, path):
return path.rstrip('/')
else:
return os.path.normpath(path)
def parse_got_revision(gclient_output, got_revision_mapping):
"""Translate git gclient revision mapping to build properties."""
properties = {}
solutions_output = {
# Make sure path always ends with a single slash.
'%s/' % path.rstrip('/') : solution_output for path, solution_output
in gclient_output['solutions'].iteritems()
}
for property_name, dir_name in got_revision_mapping.iteritems():
# Make sure dir_name always ends with a single slash.
dir_name = '%s/' % dir_name.rstrip('/')
if dir_name not in solutions_output:
continue
solution_output = solutions_output[dir_name]
if solution_output.get('scm') is None:
# This is an ignored DEPS, so the output got_revision should be 'None'.
revision = commit_position = None
else:
# Since we are using .DEPS.git, everything had better be git.
assert solution_output.get('scm') == 'git'
revision = git('rev-parse', 'HEAD', cwd=dir_name).strip()
commit_position = get_commit_position(dir_name)
properties[property_name] = revision
if commit_position:
properties['%s_cp' % property_name] = commit_position
return properties
def documentation(request, slug, path):
"""Displays the contents of a :class:`sphinxdoc.models.Document`.
``slug`` specifies the project, the document belongs to, ``path`` is the
path to the original JSON file relative to the builddir and without the
file extension. ``path`` may also be a directory, so this view checks if
``path/index`` exists, before trying to load ``path`` directly.
"""
project = get_object_or_404(Project, slug=slug)
path = path.rstrip('/')
try:
index = 'index' if path == '' else '%s/index' % path
doc = Document.objects.get(project=project, path=index)
except ObjectDoesNotExist:
doc = get_object_or_404(Document, project=project, path=path)
# genindex and modindex get a special template
templates = (
'sphinxdoc/%s.html' % os.path.basename(path),
'sphinxdoc/documentation.html',
)
try:
env = json.load(open(os.path.join(project.path, BUILDDIR,
'globalcontext.json'), 'r'))
except IOError:
# It is possible that file does not exist anymore (for example, because
# make clean to prepare for running make again), we do not want to
# display an error to the user in this case
env = None
try:
update_date = datetime.datetime.fromtimestamp(os.path.getmtime(
os.path.join(project.path, BUILDDIR, 'last_build')))
except OSError:
# It is possible that file does not exist anymore (for example, because
# make clean to prepare for running make again), we do not want to
# display an error to the user in this case
update_date = datetime.datetime.fromtimestamp(0)
data = {
'project': project,
'doc': json.loads(doc.content),
'env': env,
'update_date': update_date,
'search': urlresolvers.reverse('doc-search', kwargs={'slug': slug}),
}
return render_to_response(templates, data,
context_instance=RequestContext(request))
def run(self, context):
self.log.info('Cleaning existing files from %s', self.path)
deleteDir(self.path)
for a in self.archives:
if isinstance(a, FilteredArchiveContents):
items = [(a.getResolvedPath(context), '')]
else:
assert isinstance(a, BasePathSet)
filteredMembers = None
items = a.resolveWithDestinations(context)
for (srcAbs, destRel) in items:
if destRel and not isDirPath(destRel): destRel = os.path.dirname(destRel) # strip off the zip filename
if '..' in destRel: raise Exception('This target does not permit destination paths to contain ".." relative path expressions')
try:
filesize = os.path.getsize(srcAbs)
except Exception:
filesize = 0
self.log.info("Unpacking %s (%0.1f MB) to %s", os.path.basename(srcAbs), filesize/1024.0/1024, self.name+destRel)
starttime = time.time()
with self. __openArchive(srcAbs) as f:
mkdir(self.path+destRel)
if isinstance(a, FilteredArchiveContents) and a.hasIncludeExcludeFilters():
fullList = _getnames(f)
if not fullList:
raise BuildException('No files were found in archive "%s"'%(srcAbs))
filteredMembers = [x for x in fullList if a.isIncluded(context, x)]
self.log.info("Unpacking %d of %d members in %s", len(filteredMembers), len(fullList), os.path.basename(srcAbs))
if not filteredMembers:
raise BuildException('No files matching the specified include/exclude filters were found in archive "%s": %s'%(srcAbs, a))
if len(filteredMembers)==len(fullList):
raise BuildException('No files were excluded from the unpacking operation by the specified filters (check filters are correct): %s'%a)
else:
filteredMembers = _getnames(f)
# NB: some archive types want a list of string members, others want TarInfo objects etc, so
# if we support other archive types in future might need to do a bit of work here
path = normLongPath(self.path+destRel)
for m in filteredMembers:
if not isDirPath(m):
info = _getinfo(f, m)
if isinstance(a, FilteredArchiveContents):
_setfilename(info, a.mapDestPath(context, _getfilename(info)))
if isWindows(): _setfilename(info, _getfilename(info).replace('/', '\\'))
f.extract(info, path=path)
else:
# we should create empty directories too
if isinstance(a, FilteredArchiveContents):
m = a.mapDestPath(context, m).rstrip('/')
m = path.rstrip('/\\')+'/'+m
if isWindows(): m = m.replace('/', '\\')
mkdir(m)
self.log.info("Completed unpacking %s (%0.1f MB) in %0.1f seconds", os.path.basename(srcAbs), filesize/1024.0/1024, (time.time()-starttime))