本文整理汇总了Python中ascii函数的典型用法代码示例。如果您正苦于以下问题:Python ascii函数的具体用法?Python ascii怎么用?Python ascii使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ascii函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_ascii
def test_ascii(self):
self.assertEqual(ascii(''), '\'\'')
self.assertEqual(ascii(0), '0')
self.assertEqual(ascii(0), '0')
self.assertEqual(ascii(()), '()')
self.assertEqual(ascii([]), '[]')
self.assertEqual(ascii({}), '{}')
a = []
a.append(a)
self.assertEqual(ascii(a), '[[...]]')
a = {}
a[0] = a
self.assertEqual(ascii(a), '{0: {...}}')
# Advanced checks for unicode strings
def _check_uni(s):
self.assertEqual(ascii(s), repr(s))
_check_uni("'")
_check_uni('"')
_check_uni('"\'')
_check_uni('\0')
_check_uni('\r\n\t .')
# Unprintable non-ASCII characters
_check_uni('\x85')
_check_uni('\u1fff')
_check_uni('\U00012fff')
# Lone surrogates
_check_uni('\ud800')
_check_uni('\udfff')
# Issue #9804: surrogates should be joined even for printable
# wide characters (UCS-2 builds).
self.assertEqual(ascii('\U0001d121'), "'\\U0001d121'")
# All together
s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx."
self.assertEqual(ascii(s),
r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'""")
示例2: get_feature
def get_feature(smokey_json, feature_name):
for feature_json in smokey_json:
if feature_json['uri'] == get_feature_uri(feature_name):
return Feature(
ascii(feature_json['name']),
ascii(feature_json['uri']),
map(get_scenario, find_scenarios(feature_json)))
示例3: __init__
def __init__(self):
cmd.Cmd.__init__(self)
self.enabled_modules = enabled_modules
self.target_num = 1
self.port = 22
self.targets = {}
self.curtarget = None
proc = subprocess.Popen(
["ifconfig | grep inet | head -n1 | cut -d\ -f12 | cut -d: -f2"], stdout=subprocess.PIPE, shell=True
)
self.localIP = proc.stdout.read()
if six.PY3:
self.localIP = str(self.localIP[:-1], "utf-8")
else:
self.localIP = self.localIP[:-1].encode("ascii", "ignore").decode("ascii")
self.ctrlc = False
ascii()
print(
'Welcome to BackdoorMe, a powerful backdooring utility. Type "help" to see the list of available commands.'
)
print('Type "addtarget" to set a target, and "open" to open an SSH connection to that target.')
print("Using local IP of %s." % self.localIP)
self.addtarget("10.1.0.5", "student", "target123")
示例4: setShowInfo
def setShowInfo(self):
self.log('setShowInfo')
basex, basey = self.getControl(111 + self.focusRow).getPosition()
baseh = self.getControl(111 + self.focusRow).getHeight()
basew = self.getControl(111 + self.focusRow).getWidth()
# use the selected time to set the video
left, top = self.channelButtons[self.focusRow][self.focusIndex].getPosition()
width = self.channelButtons[self.focusRow][self.focusIndex].getWidth()
left = left - basex + (width / 2)
starttime = self.shownTime + (left / (basew / 5400.0))
chnoffset = self.focusRow - 2
newchan = self.centerChannel
while chnoffset != 0:
if chnoffset > 0:
newchan = self.MyOverlayWindow.fixChannel(newchan + 1, True)
chnoffset -= 1
else:
newchan = self.MyOverlayWindow.fixChannel(newchan - 1, False)
chnoffset += 1
plpos = self.determinePlaylistPosAtTime(starttime, newchan)
if plpos == -1:
self.log('Unable to find the proper playlist to set from EPG')
return
self.getControl(500).setLabel(self.MyOverlayWindow.channels[newchan - 1].getItemTitle(plpos))
self.getControl(501).setLabel(self.MyOverlayWindow.channels[newchan - 1].getItemEpisodeTitle(plpos))
self.getControl(502).setLabel(self.MyOverlayWindow.channels[newchan - 1].getItemDescription(plpos))
self.getControl(503).setImage(self.channelLogos + ascii(self.MyOverlayWindow.channels[newchan - 1].name) + '.png')
if not FileAccess.exists(self.channelLogos + ascii(self.MyOverlayWindow.channels[newchan - 1].name) + '.png'):
self.getControl(503).setImage(IMAGES_LOC + 'Default.png')
self.log('setShowInfo return')
示例5: generate
def generate(ui, dag, displayer, showparents, edgefn):
seen, state = [], asciistate()
for rev, type, ctx, parents in dag:
char = ctx.node() in showparents and '@' or 'o'
displayer.show(ctx)
lines = displayer.hunk.pop(rev).split('\n')[:-1]
ascii(ui, state, type, char, lines, edgefn(seen, rev, parents))
示例6: test_undecodable_env
def test_undecodable_env(self):
for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
# test str with surrogates
script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
env = os.environ.copy()
env[key] = value
# Use C locale to get ascii for the locale encoding to force
# surrogate-escaping of \xFF in the child process; otherwise it can
# be decoded as-is if the default locale is latin-1.
env['LC_ALL'] = 'C'
stdout = subprocess.check_output(
[sys.executable, "-c", script],
env=env)
stdout = stdout.rstrip(b'\n\r')
self.assertEquals(stdout.decode('ascii'), ascii(value))
# test bytes
key = key.encode("ascii", "surrogateescape")
value = value.encode("ascii", "surrogateescape")
script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
env = os.environ.copy()
env[key] = value
stdout = subprocess.check_output(
[sys.executable, "-c", script],
env=env)
stdout = stdout.rstrip(b'\n\r')
self.assertEquals(stdout.decode('ascii'), ascii(value))
示例7: goutgoing
def goutgoing(ui, repo, dest=None, **opts):
"""show the outgoing changesets alongside an ASCII revision graph
Print the outgoing changesets alongside a revision graph drawn with
ASCII characters.
Nodes printed as an @ character are parents of the working
directory.
"""
check_unsupported_flags(opts)
dest, revs, checkout = hg.parseurl(
ui.expandpath(dest or 'default-push', dest or 'default'),
opts.get('rev'))
if revs:
revs = [repo.lookup(rev) for rev in revs]
other = hg.repository(cmdutil.remoteui(ui, opts), dest)
ui.status(_('comparing with %s\n') % url.hidepassword(dest))
o = repo.findoutgoing(other, force=opts.get('force'))
if not o:
ui.status(_("no changes found\n"))
return
o = repo.changelog.nodesbetween(o, revs)[0]
revdag = graphrevs(repo, o, opts)
fmtdag = asciiformat(ui, repo, revdag, opts)
ascii(ui, asciiedges(fmtdag))
示例8: set
def set(self, key, value, ex=None, px=None, nx=False, xx=False):
"""Set key to hold the string value. If key already holds a value, it
is overwritten, regardless of its type. Any previous time to live
associated with the key is discarded on successful
:meth:`~tredis.RedisClient.set` operation.
If the value is not one of :class:`str`, :class:`bytes`, or
:class:`int`, a :exc:`ValueError` will be raised.
.. note:: **Time complexity**: ``O(1)``
:param key: The key to remove
:type key: :class:`str`, :class:`bytes`
:param value: The value to set
:type value: :class:`str`, :class:`bytes`, :class:`int`
:param int ex: Set the specified expire time, in seconds
:param int px: Set the specified expire time, in milliseconds
:param bool nx: Only set the key if it does not already exist
:param bool xx: Only set the key if it already exist
:rtype: bool
:raises: :exc:`~tredis.exceptions.RedisError`
:raises: :exc:`ValueError`
"""
command = [b'SET', key, value]
if ex:
command += [b'EX', ascii(ex).encode('ascii')]
if px:
command += [b'PX', ascii(px).encode('ascii')]
if nx:
command.append(b'NX')
if xx:
command.append(b'XX')
return self._execute(command, b'OK')
示例9: scan
def scan(self, cursor=0, pattern=None, count=None):
"""The :meth:`~tredis.RedisClient.scan` command and the closely related
commands :meth:`~tredis.RedisClient.sscan`,
:meth:`~tredis.RedisClient.hscan` and :meth:`~tredis.RedisClient.zscan`
are used in order to incrementally iterate over a collection of
elements.
- :meth:`~tredis.RedisClient.scan` iterates the set of keys in the
currently selected Redis database.
- :meth:`~tredis.RedisClient.sscan` iterates elements of Sets types.
- :meth:`~tredis.RedisClient.hscan` iterates fields of Hash types and
their associated values.
- :meth:`~tredis.RedisClient.zscan` iterates elements of Sorted Set
types and their associated scores.
**Basic usage**
:meth:`~tredis.RedisClient.scan` is a cursor based iterator.
This means that at every call of the command, the server returns an
updated cursor that the user needs to use as the cursor argument in
the next call.
An iteration starts when the cursor is set to ``0``, and terminates
when the cursor returned by the server is ``0``.
For more information on :meth:`~tredis.RedisClient.scan`,
visit the `Redis docs on scan <http://redis.io/commands/scan>`_.
.. note::
**Time complexity**: ``O(1)`` for every call. ``O(N)`` for a
complete iteration, including enough command calls for the cursor to
return back to ``0``. ``N`` is the number of elements inside the
collection.
:param int cursor: The server specified cursor value or ``0``
:param pattern: An optional pattern to apply for key matching
:type pattern: :class:`str`, :class:`bytes`
:param int count: An optional amount of work to perform in the scan
:rtype: int, list
:returns: A tuple containing the cursor and the list of keys
:raises: :exc:`~tredis.exceptions.RedisError`
"""
def format_response(value):
"""Format the response from redis
:param tuple value: The return response from redis
:rtype: tuple(int, list)
"""
return int(value[0]), value[1]
command = [b'SCAN', ascii(cursor).encode('ascii')]
if pattern:
command += [b'MATCH', pattern]
if count:
command += [b'COUNT', ascii(count).encode('ascii')]
return self._execute(command, format_callback=format_response)
示例10: graphlog
def graphlog(ui, repo, path=None, **opts):
"""show revision history alongside an ASCII revision graph
Print a revision history alongside a revision graph drawn with
ASCII characters.
Nodes printed as an @ character are parents of the working
directory.
"""
check_unsupported_flags(opts)
limit = cmdutil.loglimit(opts)
start, stop = get_revs(repo, opts["rev"])
stop = max(stop, start - limit + 1)
if start == nullrev:
return
if path:
path = util.canonpath(repo.root, os.getcwd(), path)
if path: # could be reset in canonpath
revdag = graphmod.filerevs(repo, path, start, stop)
else:
revdag = graphmod.revisions(repo, start, stop)
fmtdag = asciiformat(ui, repo, revdag, opts)
ascii(ui, asciiedges(fmtdag))
示例11: scan_number
def scan_number(self):
found_a_digit = False
found_a_decimal_point = False
whole_part = 0
fraction_part = 0.0
fraction_multiplier = 0.1
sign = 1
if self.next_char == '+':
self.advance_cursor()
elif self.next_char == '-':
sign = -1
self.advance_cursor()
while not self.end_of_expr and ((self.next_char == '.') or self.next_char.isdigit()):
if self.next_char == '.':
if found_a_decimal_point:
ScannerException.message = "badly formed number - multiple decimal points"
raise ScannerException
found_a_decimal_point = True
else:
found_a_digit = True
if not found_a_decimal_point:
whole_part = whole_part * 10 + int(self.next_char) - int(ascii(0))
else:
fraction_part += ((int(self.next_char) - int(ascii(0))) * fraction_multiplier)
fraction_multiplier /= 10
self.advance_cursor()
if not found_a_digit:
ScannerException.message = "badly formed number - no digits"
raise ScannerException
if found_a_decimal_point:
return RealToken(sign * (whole_part + fraction_part))
else:
return IntegerToken(sign * whole_part)
示例12: removeSomeReviews
def removeSomeReviews(c):
rows = c.getSession().execute('SELECT id FROM prs.users where reviews_filtered=false')
for row in rows:
logging.info("Getting reviews for user %s", row['id'])
user=models.Users.get(id=row['id'])
list=user.list_reviews
if(list is None):
user.reviews_filtered=True
user.save()
continue
list.sort(key=lambda r: r.rating, reverse=True)
index=0
for i, r in enumerate(list):
if(r.rating<3):
index=i
break
if(index>0):
list[index:] = []
list[500:] = []
user.list_reviews=[]
for r in list:
ac=models.user(id=r.actor.id, gid=r.actor.gid, name=r.actor.name, friends_count=r.actor.friends_count, reviews_count= r.actor.reviews_count,
age=r.actor.age, gender=r.actor.gender, small_user=r.actor.small_user, private=r.actor.private)
bk=models.book(id=r.book.id, gid=r.book.gid, title=ascii(r.book.title),isbn=r.book.isbn, isbn13=r.book.isbn13,
publication_date=r.book.publication_date, average_rating=r.book.average_rating,
ratings_count=r.book.ratings_count, small_book=r.book.small_book, author=r.book.author)
user.list_reviews.append(models.review(id=r.id, actor=ac, book=bk, gid=r.gid,
rating=r.rating, text=ascii(r.text)))
user.reviews_count=len(user.list_reviews)
user.reviews_filtered=True
user.save()
logging.info("Finish removing some reviews for user %s", row['id'])
开发者ID:Simone-cogno,项目名称:MT-Product-Recommender-System_improved-with-social-network-information,代码行数:32,代码来源:database_managment.py
示例13: main
def main (arg0, argv):
D("argv: " + ascii(argv))
dbfile = argv[0]
sockfile = argv[1]
logformat = "%(asctime)s %(threadName)s %(levelname)s %(message)s"
logging.basicConfig(format=logformat, level=logging.DEBUG)
logging.Formatter.converter = time.gmtime
import signal
#signal.signal(signal.SIGINT, signal.SIG_IGN)
#signal.signal(signal.SIGQUIT, signal.SIG_IGN)
#signal.signal(signal.SIGTSTP, signal.SIG_IGN)
enum_dir = "./init/enum.d"
D("initializing enums")
_init_enums_hardcoded(enum_dir)
D("creating pipes")
r, w = os.pipe()
D("pipes: r="+ascii(r)+"; w="+ascii(w))
D("doing brain")
do_brain(dbfile, sockfile, r)
D("doing readline")
do_readline(w)
D("main thread done")
示例14: comparecur
def comparecur(path_o, path_b):
list_o = os.listdir(path_o)
list_b = os.listdir(path_b)
for item_o in list_o:
# suche neue Dateien
if(not item_o in list_b):
print("new file: " + ascii(path_o + item_o))
if(os.path.isdir(path_o+item_o)):
shutil.copytree(path_o + item_o , path_b + item_o)
else:
shutil.copy2(path_o + item_o, path_b + item_o)
if(os.path.isdir(path_o + item_o)):
# durchsuche unterverzeichnis
comparecur(path_o + item_o + "/", path_b + item_o + "/" )
else:
if(os.path.getmtime(path_o+item_o)>os.path.getmtime(path_b+item_o)):
print("changed: " + ascii(path_o + item_o))
shutil.copy2(path_o+item_o, path_b+item_o)
for item_b in list_b:
if(not item_b in list_o):
if(item_b[:3]=="DEL"):
dod = int(item_b[3:11])
if(dod < int(monthago)):
print("finally deleted: " + ascii(path_b + item_b))
if (os.path.isdir(path_b+item_b)):
shutil.rmtree(path_b+item_b)
else:
os.remove(path_b + item_b)
else:
print("deleted: " + ascii(path_b + item_b))
newname_b = "DEL" + today + "__" + item_b
os.rename(path_b+item_b, path_b+newname_b)
示例15: setShowInfo
def setShowInfo(self):
self.log('setShowInfo')
if self.infoOffset > 0:
self.getControl(502).setLabel(REAL_SETTINGS.getLocalizedString(30041))
elif self.infoOffset < 0:
self.getControl(502).setLabel(REAL_SETTINGS.getLocalizedString(30042))
elif self.infoOffset == 0:
self.getControl(502).setLabel(REAL_SETTINGS.getLocalizedString(30043))
if self.hideShortItems and self.infoOffset != 0:
position = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition()
curoffset = 0
modifier = 1
if self.infoOffset < 0:
modifier = -1
while curoffset != abs(self.infoOffset):
position = self.channels[self.currentChannel - 1].fixPlaylistIndex(position + modifier)
if self.channels[self.currentChannel - 1].getItemDuration(position) >= self.shortItemLength:
curoffset += 1
else:
position = xbmc.PlayList(xbmc.PLAYLIST_MUSIC).getposition() + self.infoOffset
self.getControl(503).setLabel(self.channels[self.currentChannel - 1].getItemTitle(position))
self.getControl(504).setLabel(self.channels[self.currentChannel - 1].getItemEpisodeTitle(position))
self.getControl(505).setLabel(self.channels[self.currentChannel - 1].getItemDescription(position))
self.getControl(506).setImage(self.channelLogos + ascii(self.channels[self.currentChannel - 1].name) + '.png')
if not FileAccess.exists(self.channelLogos + ascii(self.channels[self.currentChannel - 1].name) + '.png'):
self.getControl(506).setImage(IMAGES_LOC + 'Default.png')
self.log('setShowInfo return')