• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python path.encode函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中os.path.encode函数的典型用法代码示例。如果您正苦于以下问题:Python encode函数的具体用法?Python encode怎么用?Python encode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了encode函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:yindian,项目名称:myutils,代码行数:27,代码来源:convren.py


示例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)
开发者ID:yashi,项目名称:debbindiff,代码行数:9,代码来源:cpio.py


示例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') )
开发者ID:davidhildebrand,项目名称:CATMAID,代码行数:56,代码来源:cropping.py


示例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
开发者ID:yandexdataschool,项目名称:hist_compare,代码行数:10,代码来源:utils.py


示例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")
开发者ID:spoon-today,项目名称:pyhwp,代码行数:10,代码来源:__init__.py


示例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)
开发者ID:ihacklog,项目名称:osdlyrics,代码行数:25,代码来源:utils.py


示例7: _op

 def _op(path, encodetype):
     try:
         tmp = path.encode(encodetype)
         self._chdir(tmp)
         return tmp
     except Exception as e:
         return ""
开发者ID:THCloud,项目名称:AutoInstall,代码行数:7,代码来源:helper.py


示例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'))
开发者ID:ianw,项目名称:bandersnatch,代码行数:7,代码来源:package.py


示例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
开发者ID:qman1989,项目名称:PieCrust2,代码行数:35,代码来源:page.py


示例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
开发者ID:gotgit,项目名称:doc-svn_hooks,代码行数:35,代码来源:check-case-insensitive.py


示例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)
开发者ID:burlab,项目名称:emzed,代码行数:35,代码来源:load_utils.py


示例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
开发者ID:lewissbaker,项目名称:cake,代码行数:34,代码来源:engine.py


示例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,
        })
开发者ID:urska19,项目名称:Plone-test,代码行数:34,代码来源:browser.py


示例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)
开发者ID:facebook,项目名称:watchman,代码行数:25,代码来源:path_utils.py


示例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)
开发者ID:4teamwork,项目名称:opengever.core,代码行数:25,代码来源:request.py


示例16: request

def request(host, path, url_params=None):

    url_params = url_params or {}
    url = 'http://{0}{1}?'.format(host, urllib.quote(path.encode('utf8')))

    consumer = oauth2.Consumer(CONSUMER_KEY, CONSUMER_SECRET)
    oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params)

    oauth_request.update(
        {
            'oauth_nonce': oauth2.generate_nonce(),
            'oauth_timestamp': oauth2.generate_timestamp(),
            'oauth_token': TOKEN,
            'oauth_consumer_key': CONSUMER_KEY
        }
    )
    token = oauth2.Token(TOKEN, TOKEN_SECRET)
    oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token)
    signed_url = oauth_request.to_url()
    print signed_url
    
    print u'Querying {0} ...'.format(url)

    conn = urllib2.urlopen(signed_url, None)
    response_data = conn.read()

    try:
        response = json.loads(response_data)
    finally:
        conn.close()

    return response
开发者ID:mb10,项目名称:closedbusinesses,代码行数:32,代码来源:sample.py


示例17: _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 open(path, "r", encoding="utf-8") as fp:
        raw = fp.read()
    header, offset = parse_config_header(raw)

    if "format" not 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.getAll(), "content": json_save_segments(content)}
    cache.write(cache_path, json.dumps(cache_data))

    return config, content, False
开发者ID:thhgcn,项目名称:PieCrust2,代码行数:31,代码来源:page.py


示例18: _file_url_to_local_path

 def _file_url_to_local_path(self, url):
     path = url.replace(self.mirror.master.url, '')
     path = urllib.unquote(path)
     if not path.startswith('/packages'):
         raise RuntimeError('Got invalid download URL: {}'.format(url))
     path = path[1:]
     return os.path.join(self.mirror.webdir, path.encode('utf-8'))
开发者ID:c0710204,项目名称:mirrorsBistu,代码行数:7,代码来源:package.py


示例19: __init__

 def __init__(self, path, authz, log, options={}):
     self.log = log
     self.options = options
     self.pool = Pool()
     
     if isinstance(path, unicode):
         path = path.encode('utf-8')
     path = os.path.normpath(path).replace('\\', '/')
     self.path = repos.svn_repos_find_root_path(path, self.pool())
     if self.path is None:
         raise Exception('%(path)s does not appear to be a Subversion'
                         'Repository.' % {'path': path})
     
     self.repos = repos.svn_repos_open(self.path, self.pool())
     self.fs_ptr = repos.svn_repos_fs(self.repos)
     
     uuid = fs.get_uuid(self.fs_ptr, self.pool())
     name = 'svn:%s:%s' % (uuid, _from_svn(path))
     
     if self.path != path:
         self.scope = path[len(self.path):]
         if not self.scope[-1] == '/':
             self.scope += '/'
     else:
         self.scope = '/'
     assert self.scope[0] == '/'
     self.clear()
     
     self.youngest_rev = property(lambda x: x.get_youngest_rev())
开发者ID:damoxc,项目名称:snakepit,代码行数:29,代码来源:svnclient.py


示例20: __init__

    def __init__(self, path, authz, log, options={}):
        self.log = log
        self.options = options
        self.pool = Pool()

        # Remove any trailing slash or else subversion might abort
        if isinstance(path, unicode):
            self.path = path
            path_utf8 = path.encode("utf-8")
        else:  # note that this should usually not happen (unicode arg expected)
            self.path = to_unicode(path)
            path_utf8 = self.path.encode("utf-8")
        path_utf8 = os.path.normpath(path_utf8).replace("\\", "/")
        root_path_utf8 = repos.svn_repos_find_root_path(path_utf8, self.pool())
        if root_path_utf8 is None:
            raise TracError(_("%(path)s does not appear to be a Subversion " "repository.", path=to_unicode(path_utf8)))

        try:
            self.repos = repos.svn_repos_open(root_path_utf8, self.pool())
        except core.SubversionException, e:
            raise TracError(
                _(
                    "Couldn't open Subversion repository %(path)s: " "%(svn_error)s",
                    path=to_unicode(path_utf8),
                    svn_error=exception_to_unicode(e),
                )
            )
开发者ID:gdgkyoto,项目名称:kyoto-gtug,代码行数:27,代码来源:svn_fs.py



注:本文中的os.path.encode函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python path.endswith函数代码示例发布时间:2022-05-25
下一篇:
Python path.dn函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap