本文整理汇总了Python中os.path.encode函数的典型用法代码示例。如果您正苦于以下问题:Python encode函数的具体用法?Python encode怎么用?Python encode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了encode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: renameit
def renameit(path, fromenc, toenc):
dest = path
try:
if os.name != 'nt':
ansi = path.decode(fnenc).encode(fromenc)
else:
ansi = path.encode(fromenc)
except UnicodeDecodeError:
ansi = path
except UnicodeEncodeError:
if fromenc == toenc:
ansi = path.encode(toenc, 'replace').replace('?', '_')
else:
print >> sys.stderr, 'Not of encoding %s: ' % (fromenc),
writeunicode(path, sys.stderr)
raise
global errors
try:
dest = unicode(ansi, toenc, errors)
except UnicodeDecodeError:
print >> sys.stderr, 'Cannot convert from %s to %s: ' % (fromenc,
toenc),
writeunicode(path, sys.stderr)
raise
if os.name != 'nt':
dest = dest.encode(fnenc, errors)
return (path, dest)
示例2: extract_cpio_archive
def extract_cpio_archive(path, destdir):
cmd = ['cpio', '--no-absolute-filenames', '--quiet', '-idF',
os.path.abspath(path.encode('utf-8'))]
logger.debug("extracting %s into %s", path.encode('utf-8'), destdir)
p = subprocess.Popen(cmd, shell=False, cwd=destdir)
p.communicate()
p.wait()
if p.returncode != 0:
logger.error('cpio exited with error code %d', p.returncode)
示例3: addMetaData
def addMetaData( path, job, result ):
""" Use this method to add meta data to the image. Due to a bug in
exiv2, its python wrapper pyexiv2 is of no use to us. This bug
(http://dev.exiv2.org/issues/762) hinders us to work on multi-page
TIFF files. Instead, we use a separate tool called exiftool to write
meta data. Currently, there seems no better solution than this. If the
tool is not found, no meta data is produced and no error is raised.
"""
# Add resolution information in pixel per nanometer. The stack info
# available is nm/px and refers to a zoom-level of zero.
res_x_scaled = job.ref_stack.resolution.x * 2**job.zoom_level
res_y_scaled = job.ref_stack.resolution.y * 2**job.zoom_level
res_x_nm_px = 1.0 / res_x_scaled
res_y_nm_px = 1.0 / res_y_scaled
res_args = "-EXIF:XResolution={0} -EXIF:YResolution={1} -EXIF:" \
"ResolutionUnit=None".format( str(res_x_nm_px), str(res_y_nm_px) )
# ImageJ specific meta data to allow easy embedding of units and
# display options.
n_images = len( result )
ij_version= "1.45p"
unit = "nm"
newline = "\n"
# sample with (the actual is a line break instead of a .):
# ImageJ=1.45p.images={0}.channels=1.slices=2.hyperstack=true.mode=color.unit=micron.finterval=1.spacing=1.5.loop=false.min=0.0.max=4095.0.
ij_data = "ImageJ={1}{0}unit={2}{0}".format( newline, ij_version, unit)
if n_images > 1:
n_channels = len(job.stack_mirrors)
if n_images % n_channels != 0:
raise ValueError( "Meta data creation: the number of images " \
"modulo the channel count is not zero" )
n_slices = n_images / n_channels
ij_data += "images={1}{0}channels={2}{0}slices={3}{0}hyperstack=true{0}mode=color{0}".format( newline, str(n_images), str(n_channels), str(n_slices) )
ij_args = "-EXIF:ImageDescription=\"{0}\"".format( ij_data )
# Information about the software used
sw_args = "-EXIF:Software=\"Created with CATMAID and GraphicsMagic, " \
"processed with exiftool.\""
# Build up the final tag changing arguments for each slice
tag_args = "{0} {1} {2}".format( res_args, ij_args, sw_args )
per_slice_tag_args = []
for i in range(0, n_images):
# the string EXIF gets replaced for every image with IFD<N>
slice_args = tag_args.replace( "EXIF", "IFD" + str(i) )
per_slice_tag_args.append( slice_args )
final_tag_args = " ".join( per_slice_tag_args )
# Create the final call and execute
call = "exiftool -overwrite_original {0} {1}".format( final_tag_args, path )
os.system( call )
# Re-save the image with GraphicsMagick, otherwise ImageJ won't read the
# images directly.
images = ImageList()
images.readImages( path.encode('ascii', 'ignore') )
images.writeImages( path.encode('ascii', 'ignore') )
示例4: hist_checking
def hist_checking(control_hist_location, cur_hist_location, path, technique):
with root_open(control_hist_location) as control_file, \
root_open(cur_hist_location) as cur_file:
cur_hist = cur_file.get(path.encode('ascii','ignore'))
control_hist = control_file.get(path.encode('ascii','ignore'))
if technique == 'Kolmogorov-Smirnov':
p_value = cur_hist.KolmogorovTest(control_hist)
elif technique == 'chi_square':
p_value = cur_hist.Chi2Test(control_hist)
return 1. - p_value
示例5: printstorage
def printstorage(stg, basepath=""):
names = list(stg)
names.sort()
for name in names:
path = basepath + name
item = stg[name]
if is_storage(item):
printstorage(item, path + "/")
elif is_stream(item):
print path.encode("string_escape")
示例6: path2uri
def path2uri(path):
r"""
Converts a path to URI with file sheme.
If a path does not start with a slash (/), it is considered to be an invalid
path and returned directly.
>>> path2uri('/path/to/file')
'file:///path/to/file'
>>> path2uri('file:///path/to/file')
'file:///path/to/file'
>>> path2uri(u'/path/to/file')
'file:///path/to/file'
>>> path2uri('invalid/path')
'invalid/path'
>>> path2uri('/\xe8\xb7\xaf\xe5\xbe\x84/\xe6\x96\x87\xe4\xbb\xb6')
'file:///%E8%B7%AF%E5%BE%84/%E6%96%87%E4%BB%B6'
"""
if path.startswith('~'):
path = os.path.expanduser(path)
if not path.startswith('/'):
return path
if isinstance(path, unicode):
path = path.encode('utf8')
return 'file://' + urllib.pathname2url(path)
示例7: _op
def _op(path, encodetype):
try:
tmp = path.encode(encodetype)
self._chdir(tmp)
return tmp
except Exception as e:
return ""
示例8: _file_url_to_local_path
def _file_url_to_local_path(self, url):
path = urlparse.urlparse(url).path
path = unquote(path)
if not path.startswith('/packages'):
raise RuntimeError('Got invalid download URL: {0}'.format(url))
path = path[1:]
return os.path.join(self.mirror.webdir, path.encode('utf-8'))
示例9: _do_load_page
def _do_load_page(app, path, path_mtime):
# Check the cache first.
cache = app.cache.getCache('pages')
cache_path = hashlib.md5(path.encode('utf8')).hexdigest() + '.json'
page_time = path_mtime or os.path.getmtime(path)
if cache.isValid(cache_path, page_time):
cache_data = json.loads(cache.read(cache_path),
object_pairs_hook=collections.OrderedDict)
config = PageConfiguration(values=cache_data['config'],
validate=False)
content = json_load_segments(cache_data['content'])
return config, content, True
# Nope, load the page from the source file.
logger.debug("Loading page configuration from: %s" % path)
with codecs.open(path, 'r', 'utf-8') as fp:
raw = fp.read()
header, offset = parse_config_header(raw)
if not 'format' in header:
auto_formats = app.config.get('site/auto_formats')
name, ext = os.path.splitext(path)
header['format'] = auto_formats.get(ext, None)
config = PageConfiguration(header)
content = parse_segments(raw, offset)
config.set('segments', list(content.keys()))
# Save to the cache.
cache_data = {
'config': config.get(),
'content': json_save_segments(content)}
cache.write(cache_path, json.dumps(cache_data))
return config, content, False
示例10: __init__
def __init__(self, pool, path, txn):
self.pool = pool;
repos_ptr = repos.open(path, pool)
self.fs_ptr = repos.fs(repos_ptr)
self.look = SVNLook(self.pool, path, 'changed', None, txn)
# Get the list of files and directories which have been added.
changed = self.look.cmd_changed()
if debug:
for item in changed.added + changed.addeddir:
print >> sys.stderr, 'Adding: ' + item.encode('utf-8')
if self.numadded(changed) != 0:
# Find the part of the file tree which they live in.
changedroot = self.findroot(changed)
if debug:
print >> sys.stderr, 'Changedroot is ' + changedroot.encode('utf-8')
# Get that part of the file tree.
tree = self.look.cmd_tree(changedroot)
if debug:
print >> sys.stderr, 'File tree:'
for path in tree.paths.keys():
print >> sys.stderr, ' [%d] %s len %d' % (tree.paths[path], path.encode('utf-8'), len(path))
# If a member of the paths hash has a count of more than one there is a
# case conflict.
for path in tree.paths.keys():
if tree.paths[path] > 1:
# Find out if this is one of the files being added, if not ignore it.
addedfile = self.showfile(path, changedroot, changed)
if addedfile <> '':
print >> sys.stderr, "Case conflict: " + addedfile.encode('utf-8') \
+ "\nA file with same filename but different cases already exist!"
globals()["exitstat"] = 1
示例11: loadPeakMap
def loadPeakMap(path=None):
""" loads mzXML, mzML and mzData files
If *path* is missing, a dialog for file selection is opened
instead.
"""
# local import in order to keep namespaces clean
import ms
import os.path
import sys
from pyopenms import MSExperiment, FileHandler
from libms.DataStructures import PeakMap
if isinstance(path, unicode):
path = path.encode(sys.getfilesystemencoding())
elif path is None:
path = ms.askForSingleFile(extensions="mzML mzXML mzData".split())
if path is None:
return None
# open-ms returns empty peakmap if file not exists, so we
# check ourselves:
if not os.path.exists(path):
raise Exception("file %s does not exist" % path)
if not os.path.isfile(path):
raise Exception("path %s is not a file" % path)
experiment = MSExperiment()
fh = FileHandler()
if sys.platform == "win32":
path = path.replace("/","\\") # needed for network shares
fh.loadExperiment(path, experiment)
return PeakMap.fromMSExperiment(experiment)
示例12: getByteCode
def getByteCode(self, path, cached=True):
"""Load a python file and return the compiled byte-code.
@param path: The path of the python file to load.
@type path: string
@param cached: True if the byte code should be cached to a separate
file for quicker loading next time.
@type cached: bool
@return: A code object that can be executed with the python 'exec'
statement.
@rtype: C{types.CodeType}
"""
byteCode = self._byteCodeCache.get(path, None)
if byteCode is None:
# Cache the code in a user-supplied directory if provided.
if self.scriptCachePath is not None:
assert cake.path.isAbs(path) # Need an absolute path to get a unique hash.
pathDigest = cake.hash.sha1(path.encode("utf8")).digest()
pathDigestStr = cake.hash.hexlify(pathDigest)
cacheFilePath = cake.path.join(
self.scriptCachePath,
pathDigestStr[0],
pathDigestStr[1],
pathDigestStr[2],
pathDigestStr
)
cake.filesys.makeDirs(cake.path.dirName(cacheFilePath))
else:
cacheFilePath = None
byteCode = cake.bytecode.loadCode(path, cfile=cacheFilePath, cached=cached)
self._byteCodeCache[path] = byteCode
return byteCode
示例13: delete
def delete(self, path):
"""Delete the item at the given path.
"""
path = path.encode('utf-8')
npath = self.normalizePath(path)
parentPath = '/'.join(npath.split('/')[:-1])
name = npath.split('/')[-1]
code = 0
error = ''
try:
parent = self.getObject(parentPath)
except KeyError:
error = translate(_(u'filemanager_invalid_parent',
default=u"Parent folder not found."),
context=self.request)
code = 1
else:
try:
del parent[name]
except KeyError:
error = translate(_(u'filemanager_error_file_not_found',
default=u"File not found."),
context=self.request)
code = 1
self.request.response.setHeader('Content-Type', 'application/json')
return json.dumps({
'path': self.normalizeReturnPath(path),
'error': error,
'code': code,
})
示例14: get_canonical_filesystem_path
def get_canonical_filesystem_path(name):
gfpnbh = ctypes.windll.kernel32.GetFinalPathNameByHandleW
close_handle = ctypes.windll.kernel32.CloseHandle
h = open_file_win(name)
try:
gfpnbh = ctypes.windll.kernel32.GetFinalPathNameByHandleW
numwchars = 1024
while True:
buf = ctypes.create_unicode_buffer(numwchars)
result = gfpnbh(h, buf, numwchars, 0)
if result == 0:
raise Exception("unknown error while normalizing path")
# The first four chars are //?/
if result <= numwchars:
path = buf.value[4:].replace("\\", "/")
if compat.PYTHON2:
path = path.encode("utf8")
return path
# Not big enough; the result is the amount we need
numwchars = result + 1
finally:
close_handle(h)
示例15: dispatch_request
def dispatch_request(target_admin_unit_id, viewname, path='',
data={}, headers={}):
""" Sends a request to another zope instance Returns a response stream
Authentication:
In the request there is a attribute '__cortex_ac' which is set to the
username of the current user.
:target_admin_unit_id: id of the target AdminUnit
:viewname: name of the view to call on the target
:path: context path relative to site root
:data: dict of additional data to send
:headers: dict of additional headers to send
"""
if isinstance(viewname, unicode):
viewname = viewname.encode('utf-8')
if isinstance(path, unicode):
path = path.encode('utf-8')
if get_current_admin_unit().id() == target_admin_unit_id:
return _local_request(viewname, path, data)
else:
return _remote_request(target_admin_unit_id, viewname, path,
data, headers)