本文整理汇总了Python中ascii函数的典型用法代码示例。如果您正苦于以下问题:Python ascii函数的具体用法?Python ascii怎么用?Python ascii使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ascii函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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.'""")
开发者ID:henrywoo,项目名称:Python3.1.3-Linux,代码行数:35,代码来源:test_builtin.py
示例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)))
开发者ID:gds-attic,项目名称:pp-puppet,代码行数:7,代码来源:check-smokey-test.py
示例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")
开发者ID:Kkevsterrr,项目名称:backdoorme,代码行数:25,代码来源:master.py
示例4: 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))
开发者ID:Frostman,项目名称:intellij-community,代码行数:7,代码来源:graphlog.py
示例5: 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')
开发者ID:wallacesilva,项目名称:script.pseudotv,代码行数:34,代码来源:EPGWindow.py
示例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))
开发者ID:vladistan,项目名称:py3k-__format__-sprint,代码行数:27,代码来源:test_subprocess.py
示例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))
开发者ID:wangbiaouestc,项目名称:WindowsMingWMC,代码行数:27,代码来源:graphlog.py
示例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')
开发者ID:den-t,项目名称:tredis,代码行数:34,代码来源:strings.py
示例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)
开发者ID:ibnpaul,项目名称:tredis,代码行数:60,代码来源:keys.py
示例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))
开发者ID:wangbiaouestc,项目名称:WindowsMingWMC,代码行数:26,代码来源:graphlog.py
示例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)
开发者ID:alemley,项目名称:Python-Code-Samples,代码行数:34,代码来源:ParserTest.py
示例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")
开发者ID:FoleyDiver,项目名称:Jobber,代码行数:25,代码来源:jobber.py
示例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)
开发者ID:Turysaz,项目名称:draid,代码行数:34,代码来源:mkbkup.py
示例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')
开发者ID:wallacesilva,项目名称:script.pseudotv,代码行数:35,代码来源:Overlay.py
示例16: getrange
def getrange(self, key, start, end):
"""Returns the bit value at offset in the string value stored at key.
When offset is beyond the string length, the string is assumed to be a
contiguous space with 0 bits. When key does not exist it is assumed to
be an empty string, so offset is always out of range and the value is
also assumed to be a contiguous space with 0 bits.
.. versionadded:: 0.2.0
.. note:: **Time complexity**: ``O(N)`` where ``N`` is the length of
the returned string. The complexity is ultimately determined by the
returned length, but because creating a substring from an existing
string is very cheap, it can be considered ``O(1)`` for small
strings.
:param key: The key to get the bit from
:type key: :class:`str`, :class:`bytes`
:param int start: The start position to evaluate in the string
:param int end: The end position to evaluate in the string
:rtype: bytes|None
:raises: :exc:`~tredis.exceptions.RedisError`
"""
return self._execute([b'GETRANGE', key, ascii(start), ascii(end)])
开发者ID:den-t,项目名称:tredis,代码行数:25,代码来源:strings.py
示例17: ctcp_stringify
def ctcp_stringify(messages):
"""
:type messages: ``list``
:param messages: a list of extended messages. An extended message is a
``(tag, data)`` tuple, where 'data' may be ``None``, a
``string``, or a ``list`` of strings to be joined with
white-space.
:rtype: ``str``
:returns: *Stringified* message
"""
coded_messages = []
for (tag, data) in messages:
if data:
if not isinstance(data, types.StringType):
try:
# data as list-of-strings
data = " ".join(map(str, data))
except TypeError:
# No? Then use it's %s representation.
pass
m = ascii("%s %s" % (tag, data))
else:
m = ascii(tag)
m = ctcp_quote(m)
m = ascii("%s%s%s" % (X_DELIM, m, X_DELIM))
coded_messages.append(m)
return ascii("").join(coded_messages)
开发者ID:NorthIsUp,项目名称:gIRClib,代码行数:28,代码来源:helpers.py
示例18: bitcount
def bitcount(self, key, start=None, end=None):
"""Count the number of set bits (population counting) in a string.
By default all the bytes contained in the string are examined. It is
possible to specify the counting operation only in an interval passing
the additional arguments start and end.
Like for the :meth:`~tredis.RedisClient.getrange` command start and
end can contain negative values in order to index bytes starting from
the end of the string, where ``-1`` is the last byte, ``-2`` is the
penultimate, and so forth.
Non-existent keys are treated as empty strings, so the command will
return zero.
.. versionadded:: 0.2.0
.. note:: **Time complexity**: ``O(N)``
:param key: The key to get
:type key: :class:`str`, :class:`bytes`
:param int start: The start position to evaluate in the string
:param int end: The end position to evaluate in the string
:rtype: int
:raises: :exc:`~tredis.exceptions.RedisError`, :exc:`ValueError`
"""
command = [b'BITCOUNT', key]
if start is not None and end is None:
raise ValueError('Can not specify start without an end')
elif start is None and end is not None:
raise ValueError('Can not specify start without an end')
elif start is not None and end is not None:
command += [ascii(start), ascii(end)]
return self._execute(command)
开发者ID:den-t,项目名称:tredis,代码行数:35,代码来源:strings.py
示例19: wait
def wait(self, num_slaves, timeout=0):
"""his command blocks the current client until all the previous write
commands are successfully transferred and acknowledged by at least the
specified number of slaves. If the timeout, specified in milliseconds,
is reached, the command returns even if the specified number of slaves
were not yet reached.
The command will always return the number of slaves that acknowledged
the write commands sent before the :meth:`~tredis.RedisClient.wait`
command, both in the case where the specified number of slaves are
reached, or when the timeout is reached.
.. note::
**Time complexity**: ``O(1)``
:param int num_slaves: Number of slaves to acknowledge previous writes
:param int timeout: Timeout in milliseconds
:rtype: int
:raises: :exc:`~tredis.exceptions.RedisError`
"""
command = [b'WAIT', ascii(num_slaves).encode('ascii'),
ascii(timeout).encode('ascii')]
return self._execute(command)
开发者ID:den-t,项目名称:tredis,代码行数:25,代码来源:keys.py
示例20: _store_property
def _store_property(self, path, property):
universe = property.universe
universe_path = self._get_path(universe)
if universe_path is None:
raise IOError("universe must be stored first")
element_shape = property.data.shape[1:]
if element_shape:
dtype = N.dtype((property.data.dtype, element_shape))
else:
dtype = property.data.dtype
arr = N.ascontiguousarray(property.data)
ds = self.root.require_dataset(path,
shape=(len(arr),),
dtype=dtype)
self._stamp(ds, 'property')
ds.attrs['universe'] = self.root[universe_path].ref
ds.attrs['name'] = ascii(property.name)
ds.attrs['units'] = ascii(property.units)
ds.attrs['property_type'] = ascii(property.type)
# There doesn't seem to be any way to write this array
# using high-level operations, so we use the low-level access.
mtype = h5py.h5t.py_create(ds.id.dtype)
mspace = h5py.h5s.create_simple(ds.shape)
fspace = ds.id.get_space()
ds.id.write(mspace, fspace, arr, mtype)
开发者ID:khinsen,项目名称:mosaic-python,代码行数:25,代码来源:hdf5.py
注:本文中的ascii函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论