本文整理汇总了Python中sphinx.util.force_decode函数的典型用法代码示例。如果您正苦于以下问题:Python force_decode函数的具体用法?Python force_decode怎么用?Python force_decode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了force_decode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: recurse
def recurse(cls):
if not show_builtins and cls in py_builtins:
return
if not private_bases and cls.__name__.startswith('_'):
return
nodename = self.class_name(cls, parts)
fullname = self.class_name(cls, 0)
# Use first line of docstring as tooltip, if available
tooltip = None
try:
if cls.__doc__:
enc = ModuleAnalyzer.for_module(cls.__module__).encoding
doc = cls.__doc__.strip().split("\n")[0]
if not isinstance(doc, text_type):
doc = force_decode(doc, enc)
if doc:
tooltip = '"%s"' % doc.replace('"', '\\"')
except Exception: # might raise AttributeError for strange classes
pass
baselist = []
all_classes[cls] = (nodename, fullname, baselist, tooltip)
for base in cls.__bases__:
if not show_builtins and base in py_builtins:
continue
if not private_bases and base.__name__.startswith('_'):
continue
baselist.append(self.class_name(base, parts))
if base not in all_classes:
recurse(base)
示例2: make_rst
def make_rst(self):
app = import_object(self.arguments[0])
for method, path, endpoint in get_routes(app):
try:
blueprint, endpoint_internal = endpoint.split('.')
if blueprint in self.undoc_blueprints:
continue
except ValueError:
pass # endpoint is not within a blueprint
if self.endpoints and endpoint not in self.endpoints:
continue
if endpoint in self.undoc_endpoints:
continue
try:
static_url_path = app.static_url_path # Flask 0.7 or higher
except AttributeError:
static_url_path = app.static_path # Flask 0.6 or under
if ('undoc-static' in self.options and endpoint == 'static' and
path == static_url_path + '/(path:filename)'):
continue
view = app.view_functions[endpoint]
docstring = view.__doc__ or ''
if hasattr(view, 'view_class'):
meth_func = getattr(view.view_class, method.lower(), None)
if meth_func and meth_func.__doc__:
docstring = meth_func.__doc__
if not isinstance(docstring, unicode):
analyzer = ModuleAnalyzer.for_module(view.__module__)
docstring = force_decode(docstring, analyzer.encoding)
if not docstring and 'include-empty-docstring' not in self.options:
continue
docstring = prepare_docstring(docstring)
for line in http_directive(method, path, docstring):
yield line
示例3: object_description
def object_description(object):
# type: (Any) -> unicode
"""A repr() implementation that returns text safe to use in reST context."""
if isinstance(object, dict):
try:
sorted_keys = sorted(object)
except TypeError:
pass # Cannot sort dict keys, fall back to generic repr
else:
items = ("%s: %s" %
(object_description(key), object_description(object[key]))
for key in sorted_keys)
return "{%s}" % ", ".join(items)
if isinstance(object, set):
try:
sorted_values = sorted(object)
except TypeError:
pass # Cannot sort set values, fall back to generic repr
else:
template = "{%s}" if PY3 else "set([%s])"
return template % ", ".join(object_description(x)
for x in sorted_values)
try:
s = repr(object)
except Exception:
raise ValueError
if isinstance(s, binary_type):
s = force_decode(s, None) # type: ignore
# Strip non-deterministic memory addresses such as
# ``<__main__.A at 0x7f68cb685710>``
s = memory_address_re.sub('', s)
return s.replace('\n', ' ')
示例4: get_doc
def get_doc(self, encoding=None):
content = self.env.config.autoclass_content
docstrings = []
attrdocstring = sage_getdoc_original(self.object)
if attrdocstring:
docstrings.append(attrdocstring)
# for classes, what the "docstring" is can be controlled via a
# config value; the default is only the class docstring
if content in ('both', 'init'):
initdocstring = sage_getdoc_original(
self.get_attr(self.object, '__init__', None))
# for new-style classes, no __init__ means default __init__
if initdocstring == object.__init__.__doc__:
initdocstring = None
if initdocstring:
if content == 'init':
docstrings = [initdocstring]
else:
docstrings.append(initdocstring)
doc = []
for docstring in docstrings:
if not isinstance(docstring, unicode):
docstring = force_decode(docstring, encoding)
doc.append(prepare_docstring(docstring))
return doc
示例5: get_doc
def get_doc(self, encoding=None, ignore=1):
"""Overrides ClassDocumenter.get_doc to create the doc scraped from the Process object, then adds additional
content from the class docstring.
"""
from six import text_type
# Get the class docstring. This is a copy of the ClassDocumenter.get_doc method. Using "super" does weird stuff.
docstring = self.get_attr(self.object, '__doc__', None)
# make sure we have Unicode docstrings, then sanitize and split
# into lines
if isinstance(docstring, text_type):
docstring = prepare_docstring(docstring, ignore)
elif isinstance(docstring, str): # this will not trigger on Py3
docstring = prepare_docstring(force_decode(docstring, encoding), ignore)
# Create the docstring by scraping info from the Process instance.
pdocstrings = self.make_numpy_doc()
if self.options.docstring and docstring is not None:
# Add the sections from the class docstring itself.
pdocstrings.extend(docstring[self.options.skiplines:])
# Parse using the Numpy docstring format.
docstrings = NumpyDocstring(pdocstrings, self.env.config, self.env.app, what='class', obj=self.object,
options=self.options)
return [docstrings.lines()]
示例6: add_content
def add_content(self, more_content, no_docstring=False):
if not is_mpd_running():
return
try:
cls = self.object
instance = cls(must_start_worker = False, must_handle_state = False)
try:
#instance.initialize_code()
parameter_documentation = self.get_sphinx_doc_for_parameters(instance.parameters)
finally:
instance.stop()
except Exception as ex:
print ex
return
if self.analyzer:
# prevent encoding errors when the file name is non-ASCII
filename = unicode(self.analyzer.srcname,
sys.getfilesystemencoding(), 'replace')
sourcename = u'%s:docstring of %s' % (filename, self.fullname)
else:
sourcename = u'docstring of %s' % self.fullname
encoding = self.analyzer and self.analyzer.encoding
lines = prepare_docstring(force_decode(parameter_documentation, encoding))
for i, line in enumerate(self.process_doc([lines,])):
self.add_line(line, sourcename, i)
示例7: _warn_out
def _warn_out(self, text):
self.info(text, nonl=True)
if self.app.quiet:
self.warn(text)
if isinstance(text, binary_type):
text = force_decode(text, None)
self.outfile.write(text)
示例8: get_doc
def get_doc(self, encoding=None):
"""Decode and return lines of the docstring(s) for the object."""
docstring = self.get_attr(self.object, '__doc__', None)
if docstring:
# make sure we have Unicode docstrings, then sanitize and split
# into lines
return [prepare_docstring(force_decode(docstring, encoding))]
return []
示例9: inspect_routes
def inspect_routes(self, app):
"""Inspects the views of Flask.
:param app: The Flask application.
:returns: 4-tuple like ``(method, paths, view_func, view_doc)``
"""
if self.endpoints:
routes = itertools.chain(*[get_routes(app, endpoint, self.order)
for endpoint in self.endpoints])
else:
routes = get_routes(app, order=self.order)
for method, paths, endpoint in routes:
try:
blueprint, _, endpoint_internal = endpoint.rpartition('.')
if self.blueprints and blueprint not in self.blueprints:
continue
if blueprint in self.undoc_blueprints:
continue
except ValueError:
pass # endpoint is not within a blueprint
if endpoint in self.undoc_endpoints:
continue
try:
static_url_path = app.static_url_path # Flask 0.7 or higher
except AttributeError:
static_url_path = app.static_path # Flask 0.6 or under
if ('undoc-static' in self.options and endpoint == 'static' and
static_url_path + '/(path:filename)' in paths):
continue
view = app.view_functions[endpoint]
if self.modules and view.__module__ not in self.modules:
continue
if self.undoc_modules and view.__module__ in self.modules:
continue
view_class = getattr(view, 'view_class', None)
if view_class is None:
view_func = view
else:
view_func = getattr(view_class, method.lower(), None)
view_doc = view.__doc__ or ''
if view_func and view_func.__doc__:
view_doc = view_func.__doc__
if not isinstance(view_doc, six.text_type):
analyzer = ModuleAnalyzer.for_module(view.__module__)
view_doc = force_decode(view_doc, analyzer.encoding)
if not view_doc and 'include-empty-docstring' not in self.options:
continue
yield (method, paths, view_func, view_doc)
示例10: _warn_out
def _warn_out(self, text):
# type: (unicode) -> None
if self.app.quiet or self.app.warningiserror:
logger.warning(text)
else:
logger.info(text, nonl=True)
if isinstance(text, binary_type):
text = force_decode(text, None)
self.outfile.write(text)
示例11: add_docstring
def add_docstring(docstring):
if docstring:
with IndentBlock(self):
self.add_line(u'', directive_name)
source_name = u'docstring of %s.%s' % (self.fullname, name)
docstring = [prepare_docstring(force_decode(docstring, None))]
for i, line in enumerate(self.process_doc(docstring)):
self.add_line(line, source_name, i)
self.add_line(u'', directive_name)
示例12: safe_repr
def safe_repr(object):
"""A repr() implementation that returns text safe to use in reST context."""
try:
s = repr(object)
except Exception:
raise ValueError
if isinstance(s, bytes):
return force_decode(s, None).replace('\n', ' ')
return s.replace('\n', ' ')
示例13: document_members
def document_members(self, all_members=True):
oldindent = self.indent
members = list(self.object.attributes.items())
if self.options.members is not autodoc.ALL:
specified = []
for line in (self.options.members or []):
specified.extend(line.split())
members = {
name: value for name, value in members if name in specified
}
member_order = (
self.options.member_order or self.env.config.autodoc_member_order
)
if member_order == 'alphabetical':
members.sort()
if member_order == 'groupwise':
members.sort(key=lambda e: isinstance(e[1], Method))
elif member_order == 'bysource' and self.analyzer:
name = self.object.__name__
def keyfunc(entry):
return self.analyzer.tagorder.get(
'.'.join((name, entry[0])),
len(self.analyzer.tagorder)
)
members.sort(key=keyfunc)
for name, specification in members:
self.add_line(u'', '<autointerface>')
if isinstance(specification, Method):
self.add_line(
u'.. method:: {name}{arguments}'.format(
name=name,
arguments=inspect.formatargspec(
*specification.argument_specification
)
),
'<autointerface>'
)
else:
self.add_line(
u'.. attribute:: {name}'.format(name=name),
'<autointerface>'
)
doc = specification.docstring
if doc:
self.add_line(u'', '<autointerface>')
self.indent += self.content_indent
sourcename = u'docstring of %s.%s' % (self.fullname, name)
docstrings = [prepare_docstring(force_decode(doc, None))]
for i, line in enumerate(self.process_doc(docstrings)):
self.add_line(line, sourcename, i)
self.add_line(u'', '<autointerface>')
self.indent = oldindent
示例14: _warn_out
def _warn_out(self, text):
self.info(text, nonl=True)
if self.app.quiet:
self.warn(text)
if sys.version_info >= (3,0,0):
isbytes = isinstance(text, bytes)
else:
isbytes = isinstance(text, str)
if isbytes:
text = force_decode(text, None)
self.outfile.write(text)
示例15: get_doc
def get_doc(self, encoding=None):
docstr = self.get_attr(self.object, '__doc__', None)
if docstr:
docstr = force_decode(docstr, encoding)
myname = self.fullname[len(self.modname)+1:]
if myname.endswith('()'):
myname = myname[:-2]
if (docstr
and (myname + '(') in docstr
and '\n' in docstr
and docstr[docstr.index('\n')-1] == ')'):
docstr = docstr[docstr.index('\n')+1:]
if docstr:
# make sure we have Unicode docstrings, then sanitize and split
# into lines
return [prepare_docstring(force_decode(docstr, encoding))]
return []