def test_virtualClassAttributeWithTwoMeta(self): class Meta1(type): def __dir__(cls): return ['__class__', '__module__', '__name__', 'one'] def __getattr__(self, name): if name == 'one': return 1 return super().__getattr__(name) class Meta2(type): def __dir__(cls): return ['__class__', '__module__', '__name__', 'two'] def __getattr__(self, name): if name == 'two': return 2 return super().__getattr__(name) class Meta3(Meta1, Meta2): def __dir__(cls): return list( sorted( set(['__class__', '__module__', '__name__', 'three'] + Meta1.__dir__(cls) + Meta2.__dir__(cls)))) def __getattr__(self, name): if name == 'three': return 3 return super().__getattr__(name) class Class1(metaclass=Meta1): pass class Class2(Class1, metaclass=Meta3): pass fail1 = fail2 = False output = StringIO() helper = pydoc.Helper(output=output) helper(Class1) expected_text1 = expected_virtualattribute_pattern2 % __name__ result1 = output.getvalue().strip() if result1 != expected_text1: print_diffs(expected_text1, result1) fail1 = True output = StringIO() helper = pydoc.Helper(output=output) helper(Class2) expected_text2 = expected_virtualattribute_pattern3 % __name__ result2 = output.getvalue().strip() if result2 != expected_text2: print_diffs(expected_text2, result2) fail2 = True if fail1 or fail2: self.fail("outputs are not equal, see diff above")
def get_pydoc(spec): obj = load_obj(spec) if obj: output = StringIO() pydoc.Helper(output=output).help(obj) output.seek(0) return output.read()
def test_help_output_redirect(self): # issue 940286, if output is set in Helper, then all output from # Helper.help should be redirected old_pattern = expected_text_pattern getpager_old = pydoc.getpager getpager_new = lambda: (lambda x: x) self.maxDiff = None buf = StringIO() helper = pydoc.Helper(output=buf) unused, doc_loc = get_pydoc_text(pydoc_mod) module = "test.pydoc_mod" help_header = """ Help on module test.pydoc_mod in test: """.lstrip() help_header = textwrap.dedent(help_header) expected_help_pattern = help_header + expected_text_pattern pydoc.getpager = getpager_new try: with captured_output('stdout') as output, \ captured_output('stderr') as err: helper.help(module) result = buf.getvalue().strip() expected_text = expected_help_pattern % ( (doc_loc, ) + expected_text_data_docstrings + (inspect.getabsfile(pydoc_mod), )) self.assertEqual('', output.getvalue()) self.assertEqual('', err.getvalue()) self.assertEqual(expected_text, result) finally: pydoc.getpager = getpager_old
def main(): global terminal import snappy #kernel_server = SnapPyKernelServer() terminal = SnapPyTerm() sys.stdout = terminal set_icon(terminal.window) SnapPy_ns = dict([(x, getattr(snappy,x)) for x in snappy.__all__]) #SnapPy_ns['kernel_server'] = kernel_server SnapPy_ns['exit'] = SnapPy_ns['quit'] = SnapPyExit() SnapPy_ns['pager'] = None helper = pydoc.Helper(input=terminal, output=terminal) helper.__call__ = lambda x=None : helper.help(x) if x else SnapPy_help() helper.__repr__ = lambda : help_banner SnapPy_ns['help'] = helper terminal.ipython_shell.user_ns.update(SnapPy_ns) snappy.browser.main_window = terminal LP, HP = snappy.SnapPy, snappy.SnapPyHP LP.LinkEditor = HP.LinkEditor = SnapPyLinkEditor SnapPyLinkEditor.IP = terminal.ipython_shell LP.PolyhedronViewer = HP.PolyhedronViewer = SnapPyPolyhedronViewer LP.HoroballViewer = HP.HoroballViewer = SnapPyHoroballViewer snappy.InsideViewer = SnapPyInsideViewer LP.Browser = HP.Browser = SnapPyBrowser LP.msg_stream.write = HP.msg_stream.write = terminal.write2 LP.UI_callback = HP.UI_callback = terminal.SnapPea_callback #if not snappy.SnapPy._within_sage: # snappy.pari.UI_callback = terminal.PARI_callback terminal.window.lift() terminal.window.mainloop()
def gm_help(self, obj=None): """ 获取帮助 """ import pydoc pre_classify_class_attrs = pydoc.classify_class_attrs pre_plainpager = pydoc.plainpager def my_classify_class_attrs(object): """Wrap inspect.classify_class_attrs, with fixup for data descriptors.""" new_attrs = [] attrs = pre_classify_class_attrs(object) for attr in attrs: if not object.__name__.startswith( 'GM') and not attr[0].startswith(PRE_GM): continue new_attrs.append(attr) #new_attrs.append([attr[0][4:]] + list(attr[1:])) return new_attrs def my_plainpager(text): self.log(pydoc.plain(text)) pydoc.plainpager = my_plainpager pydoc.classify_class_attrs = my_classify_class_attrs try: helper = pydoc.Helper(input=None, output=self) if obj is None: obj = self helper.help(obj) finally: pydoc.plainpager = pre_plainpager pydoc.classify_class_attrs = pre_classify_class_attrs
def main(): global terminal import snappy #kernel_server = SnapPyKernelServer() the_shell = InteractiveShellEmbed.instance( banner1=app_banner + update_needed()) terminal = SnapPyTerm(the_shell) the_shell.tkterm = terminal set_icon(terminal.window) the_shell.set_hook('show_in_pager', IPython_pager) SnapPy_ns = dict([(x, getattr(snappy,x)) for x in snappy.__all__]) #SnapPy_ns['kernel_server'] = kernel_server SnapPy_ns['exit'] = SnapPy_ns['quit'] = SnapPyExit() SnapPy_ns['pager'] = None helper = pydoc.Helper(input=terminal, output=terminal) helper.__call__ = lambda x=None : helper.help(x) if x else SnapPy_help() helper.__repr__ = lambda : help_banner SnapPy_ns['help'] = helper the_shell.user_ns.update(SnapPy_ns) snappy.browser.main_window = terminal LP, HP = snappy.SnapPy, snappy.SnapPyHP LP.LinkEditor = HP.LinkEditor = SnapPyLinkEditor SnapPyLinkEditor.IP = the_shell LP.PolyhedronViewer = HP.PolyhedronViewer = SnapPyPolyhedronViewer LP.HoroballViewer = HP.HoroballViewer = SnapPyHoroballViewer LP.Browser = HP.Browser = SnapPyBrowser LP.msg_stream.write = HP.msg_stream.write = terminal.write2 LP.UI_callback = HP.UI_callback = terminal.SnapPea_callback #if not snappy.SnapPy._within_sage: # snappy.pari.UI_callback = terminal.PARI_callback terminal.window.lift() terminal.window.mainloop()
def test_modules_search_builtin(self): expected = 'gc - ' output = StringIO() helper = pydoc.Helper(output=output) with captured_stdout() as help_io: helper('modules garbage') result = help_io.getvalue() self.assertTrue(result.startswith(expected))
def test_modules_search(self): expected = 'pydoc - ' output = StringIO() helper = pydoc.Helper(output=output) with captured_stdout() as help_io: helper('modules pydoc') result = help_io.getvalue() self.assertIn(expected, result)
def test_pydoc(self): # indirectly test __objclass__ expected_text = expected_help_output % __name__ output = StringIO() helper = pydoc.Helper(output=output) helper(self.Color) result = output.getvalue().strip() if result != expected_text: print_diffs(expected_text, result) self.fail("outputs are not equal, see diff above")
def test_modules(self): num_header_lines = 2 num_module_lines_min = 5 num_footer_lines = 3 expected = num_header_lines + num_module_lines_min + num_footer_lines output = StringIO() helper = pydoc.Helper(output=output) helper('modules') result = output.getvalue().strip() num_lines = len(result.splitlines()) self.assertGreaterEqual(num_lines, expected)
def __init__(self): self.header = ('<html><head><style type="text/css">%s</style>' '</head>\n<body>' % STYLE) self.footer = '</body></html>' self.strin = StringIO() self.strout = StringIO() self.lock = threading.Lock() self.helper = pydoc.Helper(input=self.strin, output=self.strout) self._specialtopics = set(self.helper.topics) if hasattr(self.helper, 'symbols'): self._specialtopics.update(self.helper.symbols) self._specialtopics.update(self.helper.keywords)
def test_buggy_dir(self): class M(type): def __dir__(cls): return ['__class__', '__name__', 'missing', 'here'] class C(metaclass=M): here = 'present!' output = StringIO() helper = pydoc.Helper(output=output) helper(C) expected_text = expected_missingattribute_pattern % __name__ result = output.getvalue().strip() self.assertEqual(expected_text, result)
async def help_functions(self, method): """ Lista las funciones disponibles y sus documentaciones """ m = self.items[method] if hasattr(m, "_base_function"): m = m._base_function out = io.StringIO() pydoc.Helper(output=out)(m) res = str(out.getvalue()) out.close() return res
async def list_functions(self): """ Lista las funciones disponibles y sus documentaciones """ res = {} for n, m in self.items.items(): if hasattr(m, "_base_function"): m = m._base_function out = io.StringIO() pydoc.Helper(output=out)(m) res[n] = str(out.getvalue()) out.close() return res
def test_buggy_dir(self): class M(type): def __dir__(cls): return ['__class__', '__name__', 'missing', 'here'] class C(metaclass=M): here = 'present!' output = StringIO() helper = pydoc.Helper(output=output) helper(C) expected_text = expected_missingattribute_pattern % __name__ result = output.getvalue().strip() if result != expected_text: print_diffs(expected_text, result) self.fail("outputs are not equal, see diff above")
def test_virtualClassAttributeWithOneMeta(self): class Meta(type): def __dir__(cls): return ['__class__', '__module__', '__name__', 'LIFE'] def __getattr__(self, name): if name =='LIFE': return 42 return super().__getattr(name) class Class(metaclass=Meta): pass output = StringIO() helper = pydoc.Helper(output=output) helper(Class) expected_text = expected_virtualattribute_pattern1 % __name__ result = output.getvalue().strip() self.assertEqual(expected_text, result)
def _on_plugin_init(plugin_name, plugin_desc, plugin_version, arg, libdir): global hexchat global hexchat_stdout signal.signal(signal.SIGINT, signal.SIG_DFL) plugin_name[0] = PLUGIN_NAME plugin_desc[0] = PLUGIN_DESC plugin_version[0] = PLUGIN_VERSION try: libdir = __decode(ffi.string(libdir)) modpath = os.path.join(libdir, '..', 'python') sys.path.append(os.path.abspath(modpath)) hexchat = importlib.import_module('hexchat') except (UnicodeDecodeError, ImportError) as e: lib.hexchat_print(lib.ph, b'Failed to import module: ' + repr(e).encode()) return 0 hexchat_stdout = Stdout() sys.stdout = hexchat_stdout sys.stderr = hexchat_stdout pydoc.help = pydoc.Helper(HelpEater(), HelpEater()) lib.hexchat_hook_command(lib.ph, b'', 0, lib._on_say_command, ffi.NULL, ffi.NULL) lib.hexchat_hook_command(lib.ph, b'LOAD', 0, lib._on_load_command, ffi.NULL, ffi.NULL) lib.hexchat_hook_command(lib.ph, b'UNLOAD', 0, lib._on_unload_command, ffi.NULL, ffi.NULL) lib.hexchat_hook_command(lib.ph, b'RELOAD', 0, lib._on_reload_command, ffi.NULL, ffi.NULL) lib.hexchat_hook_command( lib.ph, b'PY', 0, lib._on_py_command, b'''Usage: /PY LOAD <filename> UNLOAD <filename|name> RELOAD <filename|name> LIST EXEC <command> CONSOLE ABOUT''', ffi.NULL) lib.hexchat_print(lib.ph, b'Python interface loaded') autoload() return 1
def test_DynamicClassAttribute(self): class Meta(type): def __getattr__(self, name): if name == 'ham': return 'spam' return super().__getattr__(name) class DA(metaclass=Meta): @types.DynamicClassAttribute def ham(self): return 'eggs' expected_text_data_docstrings = tuple('\n | ' + s if s else '' for s in expected_data_docstrings) output = StringIO() helper = pydoc.Helper(output=output) helper(DA) expected_text = expected_dynamicattribute_pattern % ( (__name__,) + expected_text_data_docstrings[:2]) result = output.getvalue().strip() self.assertEqual(expected_text, result)
def _on_plugin_deinit(): global local_interp global hexchat global hexchat_stdout global plugins plugins = set() local_interp = None hexchat = None hexchat_stdout = None sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ pydoc.help = pydoc.Helper() for mod in ('_hexchat', 'hexchat', 'xchat', '_hexchat_embedded'): try: del sys.modules[mod] except KeyError: pass return 1
def my_help(*args, **kwargs): helper = pydoc.Helper(output=output) return helper(*args, **kwargs)
_orig_stdout = sys.stdout _orig_stderr = sys.stderr sys.stdout = sys.stderr = IDAPythonStdOut() # ----------------------------------------------------------------------- # Initialize the help, with our own stdin wrapper, that'll query the user # ----------------------------------------------------------------------- import pydoc class IDAPythonHelpPrompter: def readline(self): return idaapi.askstr(0, '', 'Help topic?') help = pydoc.Helper(input=IDAPythonHelpPrompter(), output=sys.stdout) # Assign a default sys.argv sys.argv = [""] # Have to make sure Python finds our modules sys.path.append(_idaapi.idadir("python")) # Remove current directory from the top of the patch search if '' in sys.path: # On non Windows, the empty path is added sys.path.remove('') if os.getcwd() in sys.path: sys.path.remove(os.getcwd()) # ...and add it to the end if needed
def __init__(self): self.helper = pydoc.Helper(sys.stdin, sys.stdout)
def __init__(self, input, output): import pydoc self._helper = pydoc.Helper(input, output)
def __init__(self): if hasattr(pydoc.Helper, "output"): # See issue #228 self.helper = pydoc.Helper(sys.stdin, None) else: self.helper = pydoc.Helper(sys.stdin, sys.stdout)
def perform(self, targs): if targs.task: try: task_class, argv, subargv, objs = load_taskclass(targs.task, [], []) except UsageError: pydoc.Helper().help(targs.task) return else: from pyloco.task import OptionTask task_class = OptionTask task = task_class(self.get_proxy()) from pyloco.plxtask import PlXTask if task_class is PlXTask: task._setup(argv[0]) if targs.template: with open(targs.template) as f: t = f.read() else: here = os.path.dirname(__file__) relpath = ("templates", "help", targs.format+"_t") tpath = os.path.join(here, *relpath) if os.path.isfile(tpath): with open(tpath) as f: t = f.read() else: t = readme_template t1 = t.replace("{", "{{").replace("}", "}}") template = t1.replace("__{{", "{").replace("}}__", "}") # read docstring and other data short_desc = "[[short description is not available.]]" long_desc = "[[long description is not available.]]" sections = {} def _extract(n1, n2, lines): if isinstance(n1, section): n1 = n1.line elif n1.line is None: import pdb; pdb.set_trace() else: n1 = n1.line-1 if n2 is None: n2 = len(lines) elif isinstance(n2, section): n2 = n2.line-3 elif n2.line is None: import pdb; pdb.set_trace() else: n2 = n2.line-1 return "\n".join(lines[n1:n2]).strip() if task.__doc__: lines = task.__doc__.splitlines() tree = publish_doctree(task.__doc__) secidx = [tree.children.index(n) for n in tree.children if isinstance(n, section)] # sections for psec, nsec in zip(secidx, secidx[1:]+[None]): pnode = tree.children[psec] nnode = None if nsec is None else tree.children[nsec] secbody = _extract(pnode, nnode, lines) for name in pnode["names"]: sections[_lowerstrip(name)] = secbody sec0 = secidx[0] if secidx else len(tree.children) paras = [n for n in tree.children[:sec0] if isinstance(n, paragraph)] if paras: tail = tree.children[secidx[0]] if secidx else None paras += [tail] if tree.children.index(paras[0]) == 0: pnode = paras[0] nnode = paras[1] short_desc = _extract(pnode, nnode, lines) if len(paras) > 2: pnode = paras[1] nnode = paras[-1] long_desc = _extract(pnode, nnode, lines) else: pnode = paras[0] nnode = paras[-1] long_desc = _extract(pnode, nnode, lines) # replace items in template env = {} env["type"] = "task" for attr in dir(task_class): if (attr.startswith("_") and attr.endswith("_") and not attr.startswith("__") and not attr.endswith("__")): env[_lowerstrip(attr[1:-1])] = str(getattr(task_class, attr)) prime = dict([(k,v) for k, v in env.items() if ("{" not in v and "}" not in v)]) for key in env.keys(): env[key] = env[key].format(**prime) env["shortdescription"] = short_desc env["longdescription"] = long_desc env.update(sections) if targs.define: for define in targs.define: for varg in vargs: env[_lowerstrip(varg)] = varg for key, value in kwargs.items(): env[_lowerstrip(key)] = value fmt = PartialFormatter() output = fmt.format(template, **env) if targs.output == "stdout": print(output) else: with open(targs.output, "w") as f: f.write(output)
def help_to_str(request: t.Any) -> str: "Call `help` on `result`, and return the result as a string" out = Output() pydoc.Helper(None, out).help(request) # type: ignore return "".join(out.results)
def help_to_str(request) -> str: out = Output() pydoc.Helper(None, out).help(request) # type: ignore return "".join(out.results)
async def Example(): @rpc_methods.register() async def Prueba2(count: int, *, vIntSchema: int = Query(..., description="mi abuela"), vInt: Union[int, float] = 1, vStr: str = "hola") -> str: a = 3 / vInt return { "count": count, "vIntSchema": vIntSchema, "vInt": vInt, "vStr": vStr, "a": a } @rpc_methods.register() async def Echo(a=1, *args, **kwargs): return (a, args, kwargs) query1 = [{ "jsonrpc": "2.0", "method": "Prueba2", "params": { "count": 5, "vIntSchema": "2a0", }, "id": 10 }, { "jsonrpc": "2.0", "method": "Prueba2", "params": { "count": 5, "vIntSchema": "20", }, "id": 11 }, { "jsonrpc": "2.0", "method": "Prueba2", "params": { "count": 5, "vIntSchema": "20", "vInt": 0, "variableSkip": 2 }, "id": 12 }] query2 = { "jsonrpc": "2.0", "method": "Prueba2", "params": { "count": 5, "vIntSchema": "20", "vStrintDiscard": "Extra argument discard" }, "id": 13 } query3 = { "jsonrpc": "2.0", "method": "Prueba2", "params": { "vIntSchema": "2a0", }, "id": 14 } query4 = { "jsonrpc": "2.0", "method": "Echo", "params": { "count": 5, "vIntSchema": "20", "vStrintDiscard": "Extra argument discard" }, "id": 13 } query5 = { "jsonrpc": "2.0", "method": "Echo", "params": [11, 2, 3], "id": 13 } await invoke_query(query1) await invoke_query(query2) await invoke_query(query3) await invoke_query(query4) await invoke_query(query5) await invoke_query({ "jsonrpc": "2.0", "method": "list", "params": ["as"], "id": 0 }) res = {} for n, m in rpc_methods.items.items(): out = io.StringIO() pydoc.Helper(output=out)(m) res[n] = str(out.getvalue()) out.close()
def __init__(self): super(HelpViewer, self).__init__("pydoc", gdb.COMMAND_OBSCURE) self.help = pydoc.Helper()