本文整理汇总了Python中pydoc.getpager函数的典型用法代码示例。如果您正苦于以下问题:Python getpager函数的具体用法?Python getpager怎么用?Python getpager使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getpager函数的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_getpager_with_stdin_none
def test_getpager_with_stdin_none(self):
previous_stdin = sys.stdin
try:
sys.stdin = None
pydoc.getpager() # Shouldn't fail.
finally:
sys.stdin = previous_stdin
示例2: __init__
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.buffer = []
self.pager = pydoc.getpager()
self.stdout_write = sys.stdout.write
self.stderr_write = sys.stderr.write
sys.stdout.write = self.write
sys.stderr.write = self.direct_write
if 'LESS' not in os.environ:
os.environ['LESS'] = '-FSRX'
global PAGER
PAGER = self
示例3: print_out
def print_out(self, txt):
import curses
txt = txt.replace("`$","\n")
#txt = txt.replace("`$","")
win=curses.initscr()
max_x, max_y = win.getmaxyx()
curses.endwin()
if len(txt.split("\n")) > max_x:
pager = pydoc.getpager()
try:
pager(txt)
except (EOFError, KeyboardInterrupt), e:
pass
示例4: run
def run(self):
_stream_tracker.stdout = self.connection
_stream_tracker.stderr = self.connection
_stream_tracker.stdin = self.connection
# Note that this is being called after we've swapped out stdout, so
# it'll give us back a plain pager
_stream_tracker.pager = pydoc.getpager()
try:
self.interact(BANNER)
except SystemExit:
print >>_former_stdout, "Remote console session disconnecting on a call to exit()"
self.connection.close()
self.connection = None
示例5: show_sample
def show_sample(module):
"""Print sample modules."""
methods_info = _extract_methods_info(module)
methods_info = sorted(methods_info, key=lambda x: x['name'])
methods_info = sorted(methods_info, key=lambda x: x['category'])
grouped_catergories = itertools.groupby(
methods_info, key=lambda x: x['category'])
text = _TEMPLATE_PREFIX.format(module_doc=_bold(module.__doc__.upper()))
nb_categories = len(set(
method_info['category'] for method_info in methods_info))
for current_category, (category_name, category_methods_info) in enumerate(
grouped_catergories):
methods_text = ''
for method_info in category_methods_info:
codelines_text = ''
for line in method_info['codelines']:
codelines_text += _CODELINE_TEMPLATE.format(codeline=line)
methods_text += _METHOD_TEMPLATE.format(
method_upper=_bold(method_info['name'].upper()),
method=_bold(method_info['name']),
doc=_bold(method_info['doc']),
result=method_info['method'](),
codelines=codelines_text.rstrip())
text += _CATEGORY_TEMPLATE.format(
step=_bold(_STEP_TEMPLATE.format(
current_category=current_category+1,
nb_categories=nb_categories)),
category=_underline(category_name.upper()),
methods=methods_text)
pydoc.getpager()(text)
示例6: print_help
def print_help(self, errors=None):
buf = cStringIO.StringIO()
sys.stdout = buf
print '='*80
optparse.OptionParser.print_help(self)
print """
examples:
"""
if errors:
print errors
sys.stdout = sys.__stdout__
pager = pydoc.getpager()
pager(buf.getvalue())
示例7: _show
def _show(self, message, log_level, *args):
r"""
Display ``message``.
.. SEEALSO::
:meth:`sage.dev.user_interface.UserInterface.show`
TESTS::
sage: from sage.dev.test.config import DoctestConfig
sage: from sage.dev.cmd_line_interface import CmdLineInterface
sage: UI = CmdLineInterface(DoctestConfig()["UI"])
sage: UI.info("I ate {0} for dinner, a whole {1} for dessert, and then took a nice walk around the lake.", 'filet mignon', 'apple pie') # indirect doctest
# I ate filet mignon for dinner, a whole apple pie for dessert, and then took a
# nice walk around the lake.
"""
if len(args) > 0:
message = message.format(*args)
height, width = self._get_dimensions()
kwds = {'width': width}
if log_level == INFO:
kwds['initial_indent'] = kwds['subsequent_indent'] = '# '
wrap = textwrap.TextWrapper(**kwds).wrap
message = list(itertools.chain.from_iterable(
wrap(line) for line in message.splitlines()))
if len(message) <= height:
print(self._color_code(log_level) +
'\n'.join(message) +
self._color_code())
else:
message = '\n'.join(message)+'\n'
try:
self._pager(message)
except AttributeError:
import pydoc
self._pager = pydoc.getpager()
self._pager(message)
示例8: lookfor
#.........这里部分代码省略.........
Parameters
----------
what : str
String containing words to look for.
module : str, module
Module whose docstrings to go through.
import_modules : bool
Whether to import sub-modules in packages.
Will import only modules in ``__all__``.
regenerate : bool
Whether to re-generate the docstring cache.
Examples
--------
>>> np.lookfor('binary representation')
Search results for 'binary representation'
------------------------------------------
numpy.binary_repr
Return the binary representation of the input number as a string.
"""
import pydoc
# Cache
cache = _lookfor_generate_cache(module, import_modules, regenerate)
# Search
# XXX: maybe using a real stemming search engine would be better?
found = []
whats = str(what).lower().split()
if not whats: return
for name, (docstring, kind, index) in cache.iteritems():
if kind in ('module', 'object'):
# don't show modules or objects
continue
ok = True
doc = docstring.lower()
for w in whats:
if w not in doc:
ok = False
break
if ok:
found.append(name)
# Relevance sort
# XXX: this is full Harrison-Stetson heuristics now,
# XXX: it probably could be improved
kind_relevance = {'func': 1000, 'class': 1000,
'module': -1000, 'object': -1000}
def relevance(name, docstr, kind, index):
r = 0
# do the keywords occur within the start of the docstring?
first_doc = "\n".join(docstr.lower().strip().split("\n")[:3])
r += sum([200 for w in whats if w in first_doc])
# do the keywords occur in the function name?
r += sum([30 for w in whats if w in name])
# is the full name long?
r += -len(name) * 5
# is the object of bad type?
r += kind_relevance.get(kind, -1000)
# is the object deep in namespace hierarchy?
r += -name.count('.') * 10
r += max(-index / 100, -100)
return r
def relevance_sort(a, b):
dr = relevance(b, *cache[b]) - relevance(a, *cache[a])
if dr != 0: return dr
else: return cmp(a, b)
found.sort(relevance_sort)
# Pretty-print
s = "Search results for '%s'" % (' '.join(whats))
help_text = [s, "-"*len(s)]
for name in found:
doc, kind, ix = cache[name]
doclines = [line.strip() for line in doc.strip().split("\n")
if line.strip()]
# find a suitable short description
try:
first_doc = doclines[0].strip()
if _function_signature_re.search(first_doc):
first_doc = doclines[1].strip()
except IndexError:
first_doc = ""
help_text.append("%s\n %s" % (name, first_doc))
# Output
if len(help_text) > 10:
pager = pydoc.getpager()
pager("\n".join(help_text))
else:
print "\n".join(help_text)
示例9: lookfor
#.........这里部分代码省略.........
Notes
-----
Relevance is determined only roughly, by checking if the keywords occur
in the function name, at the start of a docstring, etc.
Examples
--------
>>> np.lookfor('binary representation')
Search results for 'binary representation'
------------------------------------------
numpy.binary_repr
Return the binary representation of the input number as a string.
numpy.core.setup_common.long_double_representation
Given a binary dump as given by GNU od -b, look for long double
numpy.base_repr
Return a string representation of a number in the given base system.
...
"""
import pydoc
# Cache
cache = _lookfor_generate_cache(module, import_modules, regenerate)
# Search
# XXX: maybe using a real stemming search engine would be better?
found = []
whats = str(what).lower().split()
if not whats: return
for name, (docstring, kind, index) in cache.iteritems():
if kind in ('module', 'object'):
# don't show modules or objects
continue
ok = True
doc = docstring.lower()
for w in whats:
if w not in doc:
ok = False
break
if ok:
found.append(name)
# Relevance sort
# XXX: this is full Harrison-Stetson heuristics now,
# XXX: it probably could be improved
kind_relevance = {'func': 1000, 'class': 1000,
'module': -1000, 'object': -1000}
def relevance(name, docstr, kind, index):
r = 0
# do the keywords occur within the start of the docstring?
first_doc = "\n".join(docstr.lower().strip().split("\n")[:3])
r += sum([200 for w in whats if w in first_doc])
# do the keywords occur in the function name?
r += sum([30 for w in whats if w in name])
# is the full name long?
r += -len(name) * 5
# is the object of bad type?
r += kind_relevance.get(kind, -1000)
# is the object deep in namespace hierarchy?
r += -name.count('.') * 10
r += max(-index / 100, -100)
return r
def relevance_value(a):
return relevance(a, *cache[a])
found.sort(key=relevance_value)
# Pretty-print
s = "Search results for '%s'" % (' '.join(whats))
help_text = [s, "-"*len(s)]
for name in found[::-1]:
doc, kind, ix = cache[name]
doclines = [line.strip() for line in doc.strip().split("\n")
if line.strip()]
# find a suitable short description
try:
first_doc = doclines[0].strip()
if _function_signature_re.search(first_doc):
first_doc = doclines[1].strip()
except IndexError:
first_doc = ""
help_text.append("%s\n %s" % (name, first_doc))
if not found:
help_text.append("Nothing found.")
# Output
if output is not None:
output.write("\n".join(help_text))
elif len(help_text) > 10:
pager = pydoc.getpager()
pager("\n".join(help_text))
else:
print "\n".join(help_text)
示例10: __init__
def __init__(self):
self.pager = pydoc.getpager()
self.command_map = self.as_map()
示例11: dirname
import itertools
import sre_constants
import webbrowser
import subprocess
import traceback
from code import InteractiveConsole
from operator import itemgetter
from os.path import abspath, dirname, join
import logbook
from clint.textui import puts, indent, colored
from clint.textui.colored import red, green, cyan, magenta, yellow
logger = logbook.Logger('batshell')
HERE = dirname(abspath(__file__))
pager = pydoc.getpager()
try:
subprocess.check_call("echo 'test' | xsel -pi", shell=True)
except subprocess.CalledProcessError:
xsel_enabled = False
logger.warning(u'✄ Proceeding without xsel ☹')
logger.info('Please install xsel to automatically '
'copy tested regexes to the clipboard.')
else:
xsel_enabled = True
logger.info(u'✄ xsel is enabled! ☺')
def command(*aliases, **kwargs):
def decorator(f):
示例12: lookfor_f
#.........这里部分代码省略.........
String containing words to look for.
module : str, module
Module whose docstrings to go through.
import_modules : bool
Whether to import sub-modules in packages.
Will import only modules in __all__
regenerate: bool
Re-generate the docstring cache
"""
# Cache
cache = {}
for module in modules:
try:
c = self._lookfor_generate_cache(module, import_modules, regenerate)
cache.update(c)
except ImportError:
pass
# Search
# XXX: maybe using a real stemming search engine would be better?
found = []
whats = str(what).lower().split()
if not whats: return
for name, (docstring, kind, index) in cache.items():
if kind in ('module', 'object'):
# don't show modules or objects
continue
ok = True
doc = docstring.lower()
for w in whats:
if w not in doc:
ok = False
break
if ok:
found.append(name)
# Relevance sort
# XXX: this is full Harrison-Stetson heuristics now,
# XXX: it probably could be improved
kind_relevance = {'func': 1000, 'class': 1000,
'module': -1000, 'object': -1000}
def relevance(name, docstr, kind, index):
r = 0
# do the keywords occur within the start of the docstring?
first_doc = "\n".join(docstr.lower().strip().split("\n")[:3])
r += sum([200 for w in whats if w in first_doc])
# do the keywords occur in the function name?
r += sum([30 for w in whats if w in name])
# is the full name long?
r += -len(name) * 5
# is the object of bad type?
r += kind_relevance.get(kind, -1000)
# is the object deep in namespace hierarchy?
r += -name.count('.') * 10
r += max(-index / 100, -100)
return r
def relevance_sort(a, b):
dr = relevance(b, *cache[b]) - relevance(a, *cache[a])
if dr != 0: return dr
else: return (a > b) - (a < b)
# sort found according to relevance
for i in range(len(found)):
for j in range(i):
if (relevance_sort(found[j],found[j+1]) > 0):
tmp = found[j]
found[j] = found[j+1]
found[j+1] = tmp
# Pretty-print
s = "Search results for '%s'" % (' '.join(whats))
help_text = [s, "-"*len(s)]
for name in found:
doc, kind, ix = cache[name]
doclines = [line.strip() for line in doc.strip().split("\n")
if line.strip()]
# find a suitable short description
try:
first_doc = doclines[0].strip()
if _function_signature_re.search(first_doc):
first_doc = doclines[1].strip()
except IndexError:
first_doc = ""
help_text.append("%s\n %s" % (name, first_doc))
# Output
if len(help_text) > 10:
pager = pydoc.getpager()
pager("\n".join(help_text))
else:
print("\n".join(help_text))