本文整理汇总了Python中os.path.encode方法的典型用法代码示例。如果您正苦于以下问题:Python path.encode方法的具体用法?Python path.encode怎么用?Python path.encode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os.path
的用法示例。
在下文中一共展示了path.encode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setCookie
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def setCookie(self, key, value, t=None, path=None, domain=None, comment=None):
"""
sets or replace a cookies with key and value, and sets its expire time in seconds since now (if given)
"""
if isinstance(value,unicode):
value=value.encode('utf8')
self.cookies[key]=value
if t!=None:
# TODO: is this the right way of setting both expires and max-age
self.cookies[key]['expires']=time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime(time.time()+t))
if t>0: self.cookies[key]['max-age']=t
if path==None: path=self.rq.script+'/'
if isinstance(path,unicode):
path=path.encode('utf8')
self.cookies[key]['path']=path
if domain!=None: self.cookies[key]['domain']=domain
if comment!=None: self.cookies[key]['comment']=comment
示例2: formatTemplate
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def formatTemplate(rq, v, bfn=None):
"""
see http://docs.python.org/library/string.html#format-string-syntax
"""
d=rq.webapp._templatesDir
if not os.path.isdir(d): raise fileNotFoundException()
if not bfn: bfn='root.html'
fn=os.path.join(d, bfn)
#try: tmp=open(fn,'rt').read()
try: tmp=open(fn,'rt', encoding='utf8').read().decode('utf8')
except IOError: raise fileNotFoundException()
except:
rq.webapp._logger.debug('template error fn=[%s]' % fn)
raise
# Note: try is used to check for valid template
#try: s=[(tmp % v).encode('utf-8')] # NOTE: it expects a byte sequence not unicode object
try:
if isinstance(v,dict): s=tmp.format(**v)
else: s=tmp.format(*v)
except TypeError: raise KeyError
except KeyError: raise TypeError
# FIXME: use logger for above exceptions
return s
示例3: percentTemplate
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def percentTemplate(rq, v, bfn=None):
"""
see http://docs.python.org/library/stdtypes.html#string-formatting-operations
"""
d=rq.webapp._templatesDir
#rq.webapp._logger.info('template uses d=[%s]' % d)
if not os.path.isdir(d): raise fileNotFoundException()
if not bfn: bfn='root.html'
fn=os.path.join(d, bfn)
#rq.webapp._logger.info('template uses fn=[%s]' % fn)
#try: tmp=open(fn,'r').read().decode('utf8')
try: tmp=open(fn,'r', encoding='utf8').read()
except IOError: raise fileNotFoundException()
except:
rq.webapp._logger.debug('template error fn=[%s]' % fn)
raise
# Note: try is used to check for valid template
#try: s=[(tmp % v).encode('utf-8')] # NOTE: it expects a byte sequence not unicode object
try: s=tmp % v # NOTE: it expects a byte sequence not unicode object
except TypeError: raise KeyError
except KeyError: raise TypeError
# FIXME: use logger for above exceptions
return s
示例4: __getEnvWithCacheKey
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def __getEnvWithCacheKey(self, envOverrides, sandboxEnabled, platform):
# calculate start environment
if self.getPolicy("cleanEnvironment"):
osEnv = Env(os.environ)
osEnv.setFuns(self.__stringFunctions)
env = Env({ k : osEnv.substitute(v, k) for (k, v) in
self.__defaultEnv.items() })
else:
env = Env(os.environ).prune(self.__whiteList)
env.update(self.__defaultEnv)
env.setFuns(self.__stringFunctions)
env.update(envOverrides)
env["BOB_HOST_PLATFORM"] = platform
# calculate cache key for persisted packages
h = hashlib.sha1()
h.update(BOB_INPUT_HASH)
h.update(self.__cache.getDigest())
h.update(struct.pack("<I", len(env)))
for (key, val) in sorted(env.inspect().items()):
h.update(struct.pack("<II", len(key), len(val)))
h.update((key+val).encode('utf8'))
h.update(b'\x01' if sandboxEnabled else b'\x00')
return (env, h.digest())
示例5: _dirty_suffix
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def _dirty_suffix(repo, base_paths=['.']):
repo_wd = repo.working_dir
diff = repo.head.commit.diff(None)
a_hashes = _hash_blobs(d.a_blob for d in diff)
b_hashes = _hash_blobs(d.b_blob for d in diff)
u_files = repo.untracked_files
untracked_hashes = [(path, repo.git.hash_object(path)) for path in u_files]
hashes = sorted(a_hashes) + sorted(b_hashes + untracked_hashes)
filtered_hashes = [
(path, h) for path, h in hashes if _in_paths(repo_wd, base_paths, path)
]
if not filtered_hashes:
return ''
digest = hashlib.sha256()
for path, h in filtered_hashes:
digest.update(path.encode('utf-8') + b'\0' + h.encode('utf-8'))
return '-dirty-' + binascii.hexlify(digest.digest())[:12].decode('utf-8')
示例6: flat_rootname
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def flat_rootname(filename):
"""A base for a flat file name to correspond to this file.
Useful for writing files about the code where you want all the files in
the same directory, but need to differentiate same-named files from
different directories.
For example, the file a/b/c.py will return 'a_b_c_py'
"""
name = ntpath.splitdrive(filename)[1]
name = re.sub(r"[\\/.:]", "_", name)
if len(name) > MAX_FLAT:
h = hashlib.sha1(name.encode('UTF-8')).hexdigest()
name = name[-(MAX_FLAT-len(h)-1):] + '_' + h
return name
示例7: _searchForFile
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def _searchForFile(self, name):
name += '.class'
for place in self.path:
try:
archive = self._open[place]
except KeyError: # plain folder
try:
path = os.path.join(place, name)
with open(path, 'rb') as file_:
return file_.read()
except IOError:
print 'failed to open', path.encode('utf8')
else: # zip archive
try:
return archive.read(name)
except KeyError:
pass
示例8: play_channel_external
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def play_channel_external(channelname):
channelname = channelname.decode("utf8")
#channelname = urllib.quote_plus(channelname.encode("utf8"))
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')))
c = conn.cursor()
channel = c.execute("SELECT * FROM streams WHERE name=?", (channelname, )).fetchone()
if not channel:
return
uid, name, tvg_name, tvg_id, tvg_logo, groups, url = channel
if url:
cmd = [plugin.get_setting('external.player')]
args = plugin.get_setting('external.player.args')
if args:
cmd.append(args)
cmd.append(url)
#TODO shell?
subprocess.Popen(cmd,shell=windows())
示例9: search_plot_dialog
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def search_plot_dialog():
searches = plugin.get_storage('search_plot')
items = []
items.append({
"label": _("New"),
"path": plugin.url_for('search_plot_input', plot='plot'),
"thumbnail": get_icon_path('search'),
})
for search in searches:
context_items = []
context_items.append(("Delete Search" , 'XBMC.RunPlugin(%s)' % (plugin.url_for(delete_search_plot, plot=search.encode("utf8")))))
items.append({
"label": search,
"path": plugin.url_for('search_plot', plot=search.encode("utf8")),
"thumbnail": get_icon_path('search'),
'context_menu': context_items,
})
return items
示例10: search_categories_dialog
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def search_categories_dialog():
searches = plugin.get_storage('search_categories')
items = []
items.append({
"label": _("New"),
"path": plugin.url_for('search_categories_input', categories='categories'),
"thumbnail": get_icon_path('search'),
})
for search in searches:
context_items = []
context_items.append(("Delete Search" , 'XBMC.RunPlugin(%s)' % (plugin.url_for(delete_search_categories, categories=search.encode("utf8")))))
items.append({
"label": search,
"path": plugin.url_for('search_categories', categories=search.encode("utf8")),
"thumbnail": get_icon_path('search'),
'context_menu': context_items,
})
return items
示例11: tv
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def tv():
items = []
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
titles = cursor.execute('SELECT DISTINCT title FROM programmes WHERE episode IS NOT null AND episode IS NOT "MOVIE" AND start>? ORDER BY title', (datetime.utcnow(), )).fetchall()
for title_row in titles:
title = title_row[0]
items.append({
'label': title.encode("utf8"),
'path': plugin.url_for(tv_show, title=title.encode("utf8")),
'thumbnail': get_icon_path('folder'),
})
return items
示例12: movies
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def movies():
items = []
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
titles = cursor.execute('SELECT DISTINCT title, date FROM programmes WHERE episode IS "MOVIE" AND start>? ORDER BY title', (datetime.utcnow(), )).fetchall()
for title_row in titles:
title = title_row[0]
date = title_row[1] or "None"
if date == "None":
label = title
else:
label = "%s (%s)" % (title, date)
items.append({
'label': label,
'path': plugin.url_for(movie, title=title.encode("utf8"), date=date.encode("utf8")),
'thumbnail': get_icon_path('folder'),
})
return items
示例13: others
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def others():
items = []
conn = sqlite3.connect(xbmc.translatePath('%sxmltv.db' % plugin.addon.getAddonInfo('profile')), detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cursor = conn.cursor()
titles = cursor.execute('SELECT DISTINCT title,episode FROM programmes WHERE episode IS null AND start>? ORDER BY title', (datetime.utcnow(), )).fetchall()
for title_row in titles:
title = title_row[0]
label = title
items.append({
'label': label,
'path': plugin.url_for(other, title=title.encode("utf8")),
'thumbnail': get_icon_path('folder'),
})
return items
示例14: startDiscovery
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def startDiscovery(self):
if self._browser:
self._browser.cancel()
self._browser = None
self._printers = {}
instance_keys = list(self._instances.keys())
for key in instance_keys:
self.removeInstance(key)
# Add manual instances from preference
for name, properties in self._manual_instances.items():
additional_properties = {
b"path": properties["path"].encode("utf-8"),
b"useHttps": b"true" if properties.get("useHttps", False) else b"false",
b'userName': properties.get("userName", "").encode("utf-8"),
b'password': properties.get("password", "").encode("utf-8"),
b'repetier_id': properties.get("repetier_id", "").encode("utf-8"),
b"manual": b"true"
} # These additional properties use bytearrays to mimick the output of zeroconf
self.addInstance(name, properties["address"], properties["port"], additional_properties)
self.instanceListChanged.emit()
示例15: redirectException
# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import encode [as 别名]
def redirectException(location,*a,**kw):
e=webAppBaseException(302,*a,**kw)
if type(location)==unicode:
l=location.encode('utf-8')
else: l=location
e.kw['location']=l
return e