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

Python path.decode函数代码示例

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

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



在下文中一共展示了decode函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: run

def run():
    if not os.path.exists("allurl.txt"):
        fp = open("allurl.txt", "wb")
        fp.close()

    html = get_url("http://pingshu.zgpingshu.com/")
    lines = html.split("\n")
    author = None
    url = None
    name = None
    for line in lines:
        matches = re.match('<h2><a href="http://.+" target="_blank">(.+?)评书(网)?</a><span></span></h2>', line)
        if matches:
            author = matches.group(1)
            continue

        matches = re.match('^<li><a href="(http://.+?)" target="_blank">(.+?)</a></li>$', line)
        if author != None and matches != None:
            url = matches.group(1)
            name = matches.group(2)
            matches = re.match("<font color='#.{6}'>(.+)</font>", name)
            if matches:
                name = matches.group(1)
            path = "pingshu%s%s%s%s" % (os.sep, author, os.sep, name)
            if not os.path.exists(path.decode("UTF-8").encode("GBK")):
                os.makedirs(path.decode("UTF-8").encode("GBK"))
            get_menu(path, url)
开发者ID:windead,项目名称:crawl_pingshu,代码行数:27,代码来源:main.py


示例2: getFiles

def getFiles():
	log.debug("Current Files:")
	# print "Current Files:"
	curList.clear()
	for path, subdirs, files in os.walk(root):
		for name in files:
			log.debug(str(os.path.join(path))+" "+str(name))
			# print os.path.join(path.decode(sys.stdin.encoding), name.decode(sys.stdin.encoding))
			if name != ".DS_Store" and name[:2]!="._" and not "lost+found" in path and not ".etc"\
			in path:
				log.debug(str(os.path.getmtime(path+"/"+name)))
				# print os.path.getmtime(path+"/"+name)
				if name is not None and path is not None:
					curList[path.decode('UTF-8')+"/"+name.decode('UTF-8')]=os.path.getmtime(path+"/"+name)
					curList_size[path.decode('UTF-8')+"/"+name.decode('UTF-8')]=os.path.getsize(path+"/"+name)
开发者ID:ruslanmalogulko,项目名称:folder_monitor,代码行数:15,代码来源:folder_monitor.py


示例3: convertRepToXml

def convertRepToXml():
    xmlSavePath = u"E:\\app_data\\picView\\test\\rep.xml"
    repPath = u"E:\\app_data\\picView\\test\\pro_mtl.rep"
    PhoteAlbumRoot = u"F:\\url_pic_center\\meitulu"

    with open(repPath, "r") as fr:
        repObj = pickle.load(fr)

    root = Element(u"photoAlbums")
    xmlDoc = ElementTree(root)
    albumNode = insertPhotoAlbumNode(root, PhoteAlbumRoot)
    albumListNode = albumNode.find(u"subAlbums")

    subAlbumMap = {}
    for path, val in repObj.items():
        path = path.decode("gbk").encode("utf8")
        subDir, base = os.path.split(path)
        if subDir == "" or os.path.dirname(subDir) != PhoteAlbumRoot:
            print "sub dir error : %s" % os.path.dirname(subDir)
            continue
        if base == "":
            print "base name error"
            return

        subAlbumNode = None
        if subDir in subAlbumMap:
            subAlbumNode = subAlbumMap[subDir]
        else:
            subAlbumNode = insertPhotoAlbumNode(albumListNode, subDir)
            subAlbumMap.setdefault(subDir, subAlbumNode)
        setPhoto(subAlbumNode, val, base)

    xmlDoc.write(xmlSavePath, encoding="utf-8")
开发者ID:lightwang1,项目名称:myPython,代码行数:33,代码来源:tools.py


示例4: SetupPythonPaths

    def SetupPythonPaths():

        # Get the path we are in
        try:
            import xbmcaddon
            addon = xbmcaddon.Addon()
            path = addon.getAddonInfo('path')
        except:
            path = os.getcwd()

        # the XBMC libs return unicode info, so we need to convert this
        path = path.decode('utf-8')  # .encode('latin-1')
        # insert the path at the start to prevent other lib-add-ons to steal our class names
        sys.path.insert(0, os.path.join(path.replace(";", ""), 'resources', 'libs'))

        # SHOULD ONLY BE ENABLED FOR REMOTE DEBUGGING PURPOSES
        # import remotedebugger
        # debugger = remotedebugger.RemoteDebugger()

        import envcontroller
        envController = envcontroller.EnvController()
        env = envController.GetEnvironmentFolder()

        # we do use append here, because it is better to use third party libs
        # instead of the included ones.
        sys.path.append(os.path.join(path.replace(";", ""), 'resources', 'libs', env))
        return path
开发者ID:SMALLplayer,项目名称:smallplayer-image-creator,代码行数:27,代码来源:initializer.py


示例5: from_disk_add_path

 def from_disk_add_path(self, path=None, resource_list=None):
     """Add to resource_list with resources from disk scan starting at path."""
     # sanity
     if (path is None or resource_list is None or self.mapper is None):
         raise ValueError("Must specify path, resource_list and mapper")
     # is path a directory or a file? for each file: create Resource object,
     # add, increment counter
     if (sys.version_info < (3, 0)):
         path = path.decode('utf-8')
     if os.path.isdir(path):
         num_files = 0
         for dirpath, dirs, files in os.walk(path, topdown=True):
             for file_in_dirpath in files:
                 num_files += 1
                 if (num_files % 50000 == 0):
                     self.logger.info(
                         "ResourceListBuilder.from_disk_add_path: %d files..." % (num_files))
                 self.add_file(resource_list=resource_list,
                               dir=dirpath, file=file_in_dirpath)
                 # prune list of dirs based on self.exclude_dirs
                 for exclude in self.exclude_dirs:
                     if exclude in dirs:
                         self.logger.debug("Excluding dir %s" % (exclude))
                         dirs.remove(exclude)
     else:
         # single file
         self.add_file(resource_list=resource_list, file=path)
开发者ID:resync,项目名称:resync,代码行数:27,代码来源:resource_list_builder.py


示例6: download

    def download(self, path=None, name=None, req=None):
        """
        Functionality to download file
        """
        if not self.validate_request('download'):
            return {
                'Error': gettext('Not allowed'),
                'Code': 0
            }

        dir = self.dir if self.dir is not None else ''

        if hasattr(str, 'decode'):
            path = path.encode('utf-8')
            orig_path = u"{0}{1}".format(dir, path.decode('utf-8'))
        else:
            orig_path = u"{0}{1}".format(dir, path)

        try:
            Filemanager.check_access_permission(
                dir, u"{}{}".format(path, path)
            )
        except Exception as e:
            resp = Response(gettext(u"Error: {0}".format(e)))
            resp.headers['Content-Disposition'] = \
                'attachment; filename=' + name
            return resp

        name = path.split('/')[-1]
        content = open(orig_path, 'rb')
        resp = Response(content)
        resp.headers['Content-Disposition'] = 'attachment; filename=' + name
        return resp
开发者ID:thaJeztah,项目名称:pgadmin4,代码行数:33,代码来源:__init__.py


示例7: start

def start(args):
    """Set up the Geofront server URL."""
    for path in load_config_paths(CONFIG_RESOURCE):
        path = os.path.join(path.decode(), SERVER_CONFIG_FILENAME)
        if os.path.isfile(path):
            message = 'Geofront server URL is already configured: ' + path
            if args.force:
                print(message + '; overwriting...', file=sys.stderr)
            else:
                parser.exit(message)
    while True:
        server_url = input('Geofront server URL: ')
        if not server_url.startswith(('https://', 'http://')):
            print(server_url, 'is not a valid url.')
            continue
        elif not server_url.startswith('https://'):
            cont = input('It is not a secure URL. '
                         'https:// is preferred over http://. '
                         'Continue (y/N)? ')
            if cont.strip().lower() != 'y':
                continue
        break
    server_config_filename = os.path.join(
        save_config_path(CONFIG_RESOURCE).decode(),
        SERVER_CONFIG_FILENAME
    )
    with open(server_config_filename, 'w') as f:
        print(server_url, file=f)
    authenticate.call(args)
开发者ID:jckdotim,项目名称:geofront-cli,代码行数:29,代码来源:cli.py


示例8: getVideoObject

    def getVideoObject(self, params):
        self.common.log("")
        get = params.get
        
        (video, status) = self.getVideoInfo(params)

        #Check if file has been downloaded locally and use that as a source instead
        if (status == 200 and get("action", "") != "download"):
            path = self.settings.getSetting("downloadPath")
            filename = u''.join(c for c in video['Title'] if c not in self.utils.INVALID_CHARS) + u"-[" + get('videoid') + u"]" + u".mp4"
            path = os.path.join(path.decode("utf-8"), filename)
            try:
                if self.xbmcvfs.exists(path):
                    video['video_url'] = path
                    return (video, 200)
            except:
                self.common.log("attempt to locate local file failed with unknown error, trying vimeo instead")

        get = video.get
        if not video:
            # we need a scrape the homepage fallback when the api doesn't want to give us the URL
            self.common.log("getVideoObject failed because of missing video from getVideoInfo")
            return ("", 500)

        quality = self.selectVideoQuality(params, video)
        
        if ('apierror' not in video):
            if quality in video["urls"]: 
                video['video_url'] = video["urls"][quality]["url"]

            self.common.log("Done")
            return (video, 200)
        else:
            self.common.log("Got apierror: " + video['apierror'])
            return (video['apierror'], 303)
开发者ID:HenrikDK,项目名称:vimeo-xbmc-plugin,代码行数:35,代码来源:VimeoPlayer.py


示例9: update_file

	def update_file(self,hostprx,game,path):
		# game - 游戏信息
		# path - 游戏目录内的文件路径
		#
		try:
			path = path.decode('utf-8')
			self._app.getLogger().debug("begin update:(%s)"%path)
			file = "%s/%s"%(game.path,path)
			fp = open(file,'rb')
			#通知开始
			
			hostprx.syncFileStart("%s/%s"%(game.dest_path,path))
			#print "%s/%s"%(game.dest_path,path)
			while True:
				bytes = fp.read(1024*100)
				if not bytes:
					break
				hostprx.syncFileData(bytes)
			fp.close()
			hostprx.syncFileEnd()
			
			#self._app.getLogger().debug("update file succ! (%s)"%file)
		except:
			print traceback.print_exc()	
			return False
		return True
开发者ID:adoggie,项目名称:5173.com,代码行数:26,代码来源:u_sync_server.py


示例10: _toProperEncode

    def _toProperEncode(self, path):
        opath = "str"
        if path == "":
            return path
        if (type)(path) == (type)(opath):
            try:
                self._chdir(path)
                opath = path
            except Exception as e:
                opath = path.decode("utf-8").encode("gbk")
                self._chdir(opath)
        else:

            def _op(path, encodetype):
                try:
                    tmp = path.encode(encodetype)
                    self._chdir(tmp)
                    return tmp
                except Exception as e:
                    return ""

            encodeType = ["utf-8", "gbk"]
            for i in encodeType:
                tp = _op(path, i)
                if tp is not "":
                    opath = tp
                    break
        return opath
开发者ID:THCloud,项目名称:AutoInstall,代码行数:28,代码来源:helper.py


示例11: _notify

    def _notify(self, event_type, path):
        if not isinstance(path, str):
            path = path.decode('utf-8')

        name, file_ext = os.path.splitext(path)
        if file_ext == '.py':
            # remove the prefix @root from @subpath
            root = os.path.abspath(self.root_path)
            subpath = name[len(root):]
            if len(subpath) > 0 and subpath[0] == '/': subpath = subpath[1:] 

            # if we're watching /robocup/soccer/gameplay and within that, plays/my_play.py changes,
            # we extract ['plays', 'my_play'] into the @modpath list
            modpath = []
            while True:
                subpath, last_piece = os.path.split(subpath)
                modpath.insert(0, last_piece)
                if subpath == '' or subpath == '/': break

            # ignore changes to __init__.py files
            if modpath[-1] == '__init__':
                return

            logging.debug("module '" + '.'.join(modpath) + "' " + event_type)

            # call all callbacks
            for subscriber in self._subscribers:
                subscriber(event_type, modpath)
开发者ID:olivialofaro,项目名称:robocup-software,代码行数:28,代码来源:fs_watcher.py


示例12: _parse_path

    def _parse_path(self):
        """
        Parse the storage path in the config.

        Returns:
            str
        """
        if self.engine == ENGINE_DROPBOX:
            path = get_dropbox_folder_location()
        elif self.engine == ENGINE_GDRIVE:
            path = get_google_drive_folder_location()
        elif self.engine == ENGINE_COPY:
            path = get_copy_folder_location()
        elif self.engine == ENGINE_ICLOUD:
            path = get_icloud_folder_location()
        elif self.engine == ENGINE_BOX:
            path = get_box_folder_location()
        elif self.engine == ENGINE_FS:
            if self._parser.has_option('storage', 'path'):
                cfg_path = self._parser.get('storage', 'path')
                path = os.path.join(os.environ['HOME'], cfg_path)
            else:
                raise ConfigError("The required 'path' can't be found while"
                                  " the 'file_system' engine is used.")

        # Python 2 and python 3 byte strings are different.
        if sys.version_info[0] < 3:
            path = str(path)
        else:
            path = path.decode("utf-8")

        return path
开发者ID:52M,项目名称:mackup,代码行数:32,代码来源:config.py


示例13: process_childs

def process_childs(input_pipe, q_in, q_out, entries, host):
    '''Processing childs'''
    sum_size = 0
    for entry in get_data(q_in, q_out, entries):
        if entry == None:
            continue
        path, is_file, change_time, size, childs = entry

        if not is_file:
            size = process_childs(input_pipe, q_in, q_out, childs, host)

        sum_size += size

        data = {
            'path': path.decode('utf8').replace(host, ''),
            'size': size,
            'change_time': change_time,
            'is_file': is_file,
        }

        if input_pipe:
            input_pipe.send(data)
        else:
            print data['path']

    return sum_size
开发者ID:yl3dy,项目名称:amber,代码行数:26,代码来源:samba.py


示例14: 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


示例15: get_file

	def get_file(self, path):

		"""<DOC>
		Returns the path to a file. First checks if the file is in the file pool #
		and then the folder of the current experiment (if any). Otherwise, #
		simply returns the path.

		Arguments:
		path	--	The filename.

		Returns:
		The full path to the file.

		Example:
		>>> image_path = exp.get_file('my_image.png')
		>>> my_canvas = exp.offline_canvas()
		>>> my_canvas.image(image_path)
		</DOC>"""

		if not isinstance(path, basestring):
			raise osexception( \
				u"A string should be passed to experiment.get_file(), not '%s'" \
				% path)
		if isinstance(path, str):
			path = path.decode(self.encoding)
		if path.strip() == u'':
			raise osexception( \
				u"An empty string was passed to experiment.get_file(). Please specify a valid filename.")
		if os.path.exists(os.path.join(self.pool_folder, path)):
			return os.path.join(self.pool_folder, path)
		elif self.experiment_path != None and os.path.exists(os.path.join( \
			self.experiment_path, path)):
			return os.path.join(self.experiment_path, path)
		else:
			return path
开发者ID:amazinger13,项目名称:OpenSesame,代码行数:35,代码来源:experiment.py


示例16: _get_abs_path

 def _get_abs_path(exe):
     """Uses 'which' shell command to get the absolute path of the
     executable."""
     path = subprocess.check_output(['which', "%s" % exe])
     # output from subprocess, sockets etc. is bytes even in py3, so
     # convert it to unicode
     path = path.decode('utf-8')
     return path.strip('\n')
开发者ID:evelynmitchell,项目名称:vimrunner-python,代码行数:8,代码来源:vimrunner.py


示例17: __init__

 def __init__(self, path, dir_only = 0, has_dot_dot = 0):
   if isinstance(path, str): path = path.decode("latin")
   self._path              = os.path.abspath (path)
   self._is_dir            = os.path.isdir   (path)
   self.filename           = os.path.basename(path)
   self.children           = None
   self._dir_only          = dir_only
   self._has_dot_dot       = has_dot_dot
开发者ID:jdardon,项目名称:debian-pkg,代码行数:8,代码来源:qtopia_file_chooser.py


示例18: run_convert_path

    def run_convert_path(self, path, *args):
        """Run the `convert` command on a given path."""
        # The path is currently a filesystem bytestring. Convert it to
        # an argument bytestring.
        path = path.decode(util._fsencoding()).encode(ui._arg_encoding())

        args = args + (b'path:' + path,)
        return self.run_command('convert', *args)
开发者ID:pszxzsd,项目名称:beets,代码行数:8,代码来源:test_convert.py


示例19: get_server_url

def get_server_url():
    for path in load_config_paths(CONFIG_RESOURCE):
        path = os.path.join(path.decode(), SERVER_CONFIG_FILENAME)
        if os.path.isfile(path):
            with open(path) as f:
                return f.read().strip()
    parser.exit('Geofront server URL is not configured yet.\n'
                'Try `{0} start` command.'.format(parser.prog))
开发者ID:jckdotim,项目名称:geofront-cli,代码行数:8,代码来源:cli.py


示例20: decode_path

def decode_path(path):
    """
    Decode file/path string. Return `nodes.reprunicode` object.

    Convert to Unicode without the UnicodeDecode error of the
    implicit 'ascii:strict' decoding.
    """
    # see also http://article.gmane.org/gmane.text.docutils.user/2905
    try:
        path = path.decode(sys.getfilesystemencoding(), 'strict')
    except AttributeError: # default value None has no decode method
        return nodes.reprunicode(path)
    except UnicodeDecodeError:
        try:
            path = path.decode('utf-8', 'strict')
        except UnicodeDecodeError:
            path = path.decode('ascii', 'replace')
    return nodes.reprunicode(path)
开发者ID:Naviacom,项目名称:Configurations,代码行数:18,代码来源:utils.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python path.dirname函数代码示例发布时间:2022-05-25
下一篇:
Python path.commonprefix函数代码示例发布时间: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