本文整理汇总了Python中reprlib.repr函数的典型用法代码示例。如果您正苦于以下问题:Python repr函数的具体用法?Python repr怎么用?Python repr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了repr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: format_stack_entry
def format_stack_entry(self, frame_lineno, lprefix=': '):
"""Return a string with information about a stack entry.
The stack entry frame_lineno is a (frame, lineno) tuple. The
return string contains the canonical filename, the function name
or '<lambda>', the input arguments, the return value, and the
line of code (if it exists).
"""
import linecache, reprlib
frame, lineno = frame_lineno
filename = self.canonic(frame.f_code.co_filename)
s = '%s(%r)' % (filename, lineno)
if frame.f_code.co_name:
s += frame.f_code.co_name
else:
s += "<lambda>"
if '__args__' in frame.f_locals:
args = frame.f_locals['__args__']
else:
args = None
if args:
s += reprlib.repr(args)
else:
s += '()'
if '__return__' in frame.f_locals:
rv = frame.f_locals['__return__']
s += '->'
s += reprlib.repr(rv)
line = linecache.getline(filename, lineno, frame.f_globals)
if line:
s += lprefix + line.strip()
return s
示例2: format_stack_entry
def format_stack_entry(self, frame_lineno, lprefix=": ", context=3):
try:
import reprlib # Py 3
except ImportError:
import repr as reprlib # Py 2
ret = []
Colors = self.color_scheme_table.active_colors
ColorsNormal = Colors.Normal
tpl_link = u"%s%%s%s" % (Colors.filenameEm, ColorsNormal)
tpl_call = u"%s%%s%s%%s%s" % (Colors.vName, Colors.valEm, ColorsNormal)
tpl_line = u"%%s%s%%s %s%%s" % (Colors.lineno, ColorsNormal)
tpl_line_em = u"%%s%s%%s %s%%s%s" % (Colors.linenoEm, Colors.line, ColorsNormal)
frame, lineno = frame_lineno
return_value = ""
if "__return__" in frame.f_locals:
rv = frame.f_locals["__return__"]
# return_value += '->'
return_value += reprlib.repr(rv) + "\n"
ret.append(return_value)
# s = filename + '(' + `lineno` + ')'
filename = self.canonic(frame.f_code.co_filename)
link = tpl_link % py3compat.cast_unicode(filename)
if frame.f_code.co_name:
func = frame.f_code.co_name
else:
func = "<lambda>"
call = ""
if func != "?":
if "__args__" in frame.f_locals:
args = reprlib.repr(frame.f_locals["__args__"])
else:
args = "()"
call = tpl_call % (func, args)
# The level info should be generated in the same format pdb uses, to
# avoid breaking the pdbtrack functionality of python-mode in *emacs.
if frame is self.curframe:
ret.append("> ")
else:
ret.append(" ")
ret.append(u"%s(%s)%s\n" % (link, lineno, call))
start = lineno - 1 - context // 2
lines = ulinecache.getlines(filename)
start = min(start, len(lines) - context)
start = max(start, 0)
lines = lines[start : start + context]
for i, line in enumerate(lines):
show_arrow = start + 1 + i == lineno
linetpl = (frame is self.curframe or show_arrow) and tpl_line_em or tpl_line
ret.append(self.__format_line(linetpl, filename, start + 1 + i, line, arrow=show_arrow))
return "".join(ret)
示例3: format_stack_entry
def format_stack_entry(self, frame_lineno, lprefix=': '):
import linecache
import reprlib
(frame, lineno) = frame_lineno
filename = self.canonic(frame.f_code.co_filename)
s = '%s(%r)' % (filename, lineno)
if frame.f_code.co_name:
s += frame.f_code.co_name
else:
s += '<lambda>'
if '__args__' in frame.f_locals:
args = frame.f_locals['__args__']
else:
args = None
if args:
s += reprlib.repr(args)
else:
s += '()'
if '__return__' in frame.f_locals:
rv = frame.f_locals['__return__']
s += '->'
s += reprlib.repr(rv)
line = linecache.getline(filename, lineno, frame.f_globals)
if line:
s += lprefix + line.strip()
return s
示例4: _dorequest
def _dorequest(self, rf, wf):
rp = pickle.Unpickler(rf)
try:
request = rp.load()
except EOFError:
return 0
if self._verbose > 1: print("Got request: %s" % repr(request))
try:
methodname, args, id = request
if '.' in methodname:
reply = (None, self._special(methodname, args), id)
elif methodname[0] == '_':
raise NameError("illegal method name %s" % repr(methodname))
else:
method = getattr(self, methodname)
reply = (None, method(*args), id)
except:
reply = (sys.exc_info()[:2], id)
if id < 0 and reply[:2] == (None, None):
if self._verbose > 1: print("Suppress reply")
return 1
if self._verbose > 1: print("Send reply: %s" % repr(reply))
wp = pickle.Pickler(wf)
wp.dump(reply)
return 1
示例5: __repr__
def __repr__(self):
"Dunder method that gives a string representation for the programmer"
class_name = type(self).__name__
components = reprlib.repr(list(itertools.islice(self._times, 0, 10)))
components2 = reprlib.repr(list(itertools.islice(self._values, 0, 10)))
components = components[components.find('['):]
components2 = components2[components2.find('['):]
return '{}({}, {})'.format(class_name, components, components2)
示例6: echo_cli
def echo_cli( number, reps ):
log.normal( "Echo Client %3d connecting... PID [%5d]", number, os.getpid() )
conn = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
conn.connect( echo.address )
log.detail( "Echo Client %3d connected", number )
sent = b''
rcvd = b''
try:
# Send messages and collect replies 'til done (or incoming EOF). Then, shut down
# outgoing half of socket to drain server and shut down server.
eof = False
for r in range( reps ):
msg = ("Client %3d, rep %d\r\n" % ( number, r )).encode()
log.detail("Echo Client %3d send: %5d: %s", number, len( msg ), reprlib.repr( msg ))
sent += msg
while len( msg ) and not eof:
out = min( len( msg ), random.randrange( *charrange ))
conn.send( msg[:out] )
msg = msg[out:]
# Await inter-block chardelay if output remains, otherwise await final response
# before dropping out to shutdown/drain/close. If we drop out immediately and send
# a socket.shutdown, it'll sometimes deliver a reset to the server end of the
# socket, before delivering the last of the data.
rpy = network.recv( conn, timeout=chardelay if len( msg ) else draindelay )
if rpy is not None:
eof = not len( rpy )
log.detail( "Echo Client %3d recv: %5d: %s", number, len( rpy ),
"EOF" if eof else reprlib.repr( rpy ))
rcvd += rpy
if eof:
break
log.normal( "Echo Client %3d done; %s", number, "due to EOF" if eof else "normal termination" )
except KeyboardInterrupt as exc:
log.warning( "Echo Client %3d terminated: %r", number, exc )
except Exception as exc:
log.warning( "Echo Client %3d failed: %r\n%s", number, exc, traceback.format_exc() )
finally:
# One or more packets may be in flight; wait 'til we timeout/EOF. This shuts down conn.
rpy = network.drain( conn, timeout=draindelay )
log.info( "Echo Client %3d drain %5d: %s", number, len( rpy ) if rpy is not None else 0,
reprlib.repr( rpy ))
if rpy is not None:
rcvd += rpy
# Count the number of success/failures reported by the Echo client threads
failed = not ( rcvd == sent )
if failed:
log.warning( "Echo Client %3d failed: %s != %s sent", number, reprlib.repr( rcvd ),
reprlib.repr( sent ))
log.info( "Echo Client %3d exited", number )
return failed
示例7: __repr__
def __repr__(self):
"""
Only prints the first six times and values of the time series
"""
class_name = type(self).__name__
t_components = reprlib.repr(list(itertools.islice(self._times, 0, len(self))))
t_components = t_components[t_components.find('['):]
v_components = reprlib.repr(list(itertools.islice(self._values, 0, len(self))))
v_components = v_components[v_components.find('['):]
return "{}(times=({}, values={}))".format(class_name, t_components, v_components)
示例8: __str__
def __str__(self):
"""
Dunder method that gives a shortened string representation of the TimeSeries
[time1, time2, ...], [value1, value2, ...]
"""
components = reprlib.repr(list(itertools.islice(self._times, 0, 10)))
components2 = reprlib.repr(list(itertools.islice(self._values, 0, 10)))
components = components[components.find('['):]
components2 = components2[components2.find('['):]
return '{}, {}'.format(components, components2)
示例9: __str__
def __str__(self):
"""
Only prints the first six times and values of the time series, in a human readable way.
"""
class_name = type(self).__name__
t_components = reprlib.repr(list(itertools.islice(self._times, 0, len(self))))
t_components = t_components[t_components.find('['):]
v_components = reprlib.repr(list(itertools.islice(self._values, 0, len(self))))
v_components = v_components[v_components.find('['):]
return "{} with {} elements: ({}, {})".format(class_name, len(self._times),
t_components, v_components)
示例10: _format_args_and_kwargs
def _format_args_and_kwargs(args, kwargs):
"""Format function arguments and keyword arguments.
Special case for a single parameter: ('hello',) is formatted as ('hello').
"""
# use reprlib to limit the length of the output
items = []
if args:
items.extend(reprlib.repr(arg) for arg in args)
if kwargs:
items.extend('{}={}'.format(k, reprlib.repr(v)) for k, v in kwargs.items())
return '({})'.format(', '.join(items))
示例11: _serve
def _serve(self):
if self._verbose: print("Wait for connection ...")
conn, address = self._socket.accept()
if self._verbose: print("Accepted connection from %s" % repr(address))
if not self._verify(conn, address):
print("*** Connection from %s refused" % repr(address))
conn.close()
return
rf = conn.makefile('r')
wf = conn.makefile('w')
ok = 1
while ok:
wf.flush()
if self._verbose > 1: print("Wait for next request ...")
ok = self._dorequest(rf, wf)
示例12: dump
def dump(obj):
print("Type")
print("====")
print(type(obj))
print()
print("Documentation")
print("=============")
# print(obj.__doc__)
print(inspect.getdoc(obj))
print()
print("Attributes")
print("==========")
all_attr_names = SortedSet(dir(obj))
method_names = SortedSet(
filter(lambda attr_name: callable(getattr(obj, attr_name)),
all_attr_names)
)
assert method_names <= all_attr_names
attr_names = all_attr_names - method_names
attr_names_and_values = [(name, reprlib.repr(getattr(obj, name)))
for name in attr_names]
print_table(attr_names_and_values, "Name", "Value")
print()
print("Methods")
print("=======")
methods = (getattr(obj, method_name) for method_name in method_names)
method_names_and_doc = [(full_sig(method), brief_doc(method))
for method in methods]
print_table(method_names_and_doc, "Name", "Description")
print()
示例13: echo_server
def echo_server( conn, addr ):
"""Serve one echo client 'til EOF; then close the socket"""
source = cpppo.chainable()
with echo_machine( "echo_%s" % addr[1] ) as echo_line:
eof = False
while not eof:
data = cpppo.dotdict()
# See if a line has been recognized, stopping at terminal state. If this machine
# is ended early due to an EOF, it should still terminate in a terminal state
for mch, sta in echo_line.run( source=source, data=data ):
if sta is not None:
continue
# Non-transition; check for input, blocking if non-terminal and none left. On
# EOF, terminate early; this will raise a GeneratorExit.
timeout = 0 if echo_line.terminal or source.peek() is not None else None
msg = network.recv( conn, timeout=timeout )
if msg is not None:
eof = not len( msg )
log.info( "%s recv: %5d: %s", echo_line.name_centered(), len( msg ),
"EOF" if eof else reprlib.repr( msg ))
source.chain( msg )
if eof:
break
# Terminal state (or EOF).
log.detail( "%s: byte %5d: data: %r", echo_line.name_centered(), source.sent, data )
if echo_line.terminal:
conn.send( data.echo )
log.info( "%s done", echo_line.name_centered() )
示例14: __repr__
def __repr__(self):
return '{}({}, {}, {}, {})'.format(
self.__class__.__name__,
self.key_min(),
self.key_max(),
self._key_stride,
reprlib.repr(self._values))
示例15: tnet_server
def tnet_server( conn, addr ):
"""Serve one tnet client 'til EOF; then close the socket"""
source = cpppo.chainable()
with tnet_machine( "tnet_%s" % addr[1] ) as tnet_mesg:
eof = False
while not eof:
data = cpppo.dotdict()
# Loop blocking for input, while we've consumed input from source since the last time.
# If we hit this again without having used any input, we know we've hit a symbol
# unacceptable to the state machine; stop
for mch, sta in tnet_mesg.run( source=source, data=data ):
if sta is not None:
continue
# Non-transition; check for input, blocking if non-terminal and none left. On
# EOF, terminate early; this will raise a GeneratorExit.
timeout = 0 if tnet_mesg.terminal or source.peek() is not None else None
msg = network.recv( conn, timeout=timeout ) # blocking
if msg is not None:
eof = not len( msg )
log.info( "%s: recv: %5d: %s", tnet_mesg.name_centered(), len( msg ),
"EOF" if eof else reprlib.repr( msg ))
source.chain( msg )
if eof:
break
# Terminal state (or EOF).
log.detail( "%s: byte %5d: data: %r", tnet_mesg.name_centered(), source.sent, data )
if tnet_mesg.terminal:
res = json.dumps( data.tnet.type.input, indent=4, sort_keys=True )
conn.send(( res + "\n\n" ).encode( "utf-8" ))
log.info( "%s done", tnet_mesg.name_centered() )