def opt_help_reactors(self): """ Display a list of possibly available reactor names. """ for r in reactors.getReactorTypes(): print ' ', r.shortName, '\t', r.description raise SystemExit(0)
def opt_help_reactors(self): """Display a list of available reactors""" from twisted.application import reactors for r in reactors.getReactorTypes(): sys.stdout.write(' %-4s\t%s\n' % (r.shortName, r.description)) raise SystemExit(0)
def opt_help_reactors(self): """ Display a list of possibly available reactor names. """ for r in reactors.getReactorTypes(): self.messageOutput.write(' %-4s\t%s\n' % (r.shortName, r.description)) raise SystemExit(0)
def _init_reactor_map(__reactor_map=OrderedDict()): if not __reactor_map: from twisted.application import reactors # Delay the import of twisted.plugins as long as possible for r in reactors.getReactorTypes(): try: m = importlib.import_module(r.moduleName) except ImportError: continue if m.__name__ != m.install.__module__: m = importlib.import_module(m.install.__module__) __reactor_map[r.shortName] = m assert __reactor_map return __reactor_map
def test_getPluginReactorTypes(self): """ Test that reactor plugins are returned from L{getReactorTypes} """ name = "fakereactortest" package = __name__ + ".fakereactor" description = "description" self.pluginResults = [reactors.Reactor(name, package, description)] reactorTypes = reactors.getReactorTypes() self.assertEqual(self.pluginCalls, [(reactors.IReactorInstaller, None)]) for r in reactorTypes: if r.shortName == name: self.assertEqual(r.description, description) break else: self.fail("Reactor plugin not present in getReactorTypes() result")
def main(args=None, locals_=None, banner=None): translations.init() def options_callback(group): group.add_argument( "--twisted", "-T", action="store_true", help=_("Run twisted reactor."), ) group.add_argument( "--reactor", "-r", help=_("Select specific reactor (see --help-reactors). " "Implies --twisted."), ) group.add_argument( "--help-reactors", action="store_true", help=_("List available reactors for -r."), ) group.add_argument( "--plugin", "-p", help=_("twistd plugin to run (use twistd for a list). " 'Use "--" to pass further options to the plugin.'), ) group.add_argument( "--server", "-s", type=int, help=_("Port to run an eval server on (forces Twisted)."), ) # TODO: maybe support displays other than raw_display? config, options, exec_args = bpargs.parse( args, ( "Urwid options", None, options_callback, ), ) if options.help_reactors: try: from twisted.application import reactors # Stolen from twisted.application.app (twistd). for r in reactors.getReactorTypes(): print(f" {r.shortName:<4}\t{r.description}") except ImportError: sys.stderr.write("No reactors are available. Please install " "twisted for reactor support.\n") return palette = [( name, COLORMAP[color.lower()], "default", "bold" if color.isupper() else "default", ) for name, color in config.color_scheme.items()] palette.extend([("bold " + name, color + ",bold", background, monochrome) for name, color, background, monochrome in palette]) if options.server or options.plugin: options.twisted = True if options.reactor: try: from twisted.application import reactors except ImportError: sys.stderr.write("No reactors are available. Please install " "twisted for reactor support.\n") return try: # XXX why does this not just return the reactor it installed? reactor = reactors.installReactor(options.reactor) if reactor is None: from twisted.internet import reactor except reactors.NoSuchReactor: sys.stderr.write(f"Reactor {options.reactor} does not exist\n") return event_loop = TwistedEventLoop(reactor) elif options.twisted: try: from twisted.internet import reactor except ImportError: sys.stderr.write("No reactors are available. Please install " "twisted for reactor support.\n") return event_loop = TwistedEventLoop(reactor) else: # None, not urwid.SelectEventLoop(), to work with # screens that do not support external event loops. event_loop = None # TODO: there is also a glib event loop. Do we want that one? extend_locals = {} if options.plugin: try: from twisted import plugin from twisted.application import service except ImportError: sys.stderr.write( "No twisted plugins are available. Please install " "twisted for twisted plugin support.\n") return for plug in plugin.getPlugins(service.IServiceMaker): if plug.tapname == options.plugin: break else: sys.stderr.write(f"Plugin {options.plugin} does not exist\n") return plugopts = plug.options() plugopts.parseOptions(exec_args) serv = plug.makeService(plugopts) extend_locals["service"] = serv reactor.callWhenRunning(serv.startService) exec_args = [] interpreter = repl.Interpreter(locals_, locale.getpreferredencoding()) # TODO: replace with something less hack-ish interpreter.locals.update(extend_locals) # This nabs sys.stdin/out via urwid.MainLoop myrepl = URWIDRepl(event_loop, palette, interpreter, config) if options.server: factory = EvalFactory(myrepl) reactor.listenTCP(options.server, factory, interface="127.0.0.1") if options.reactor: # Twisted sets a sigInt handler that stops the reactor unless # it sees a different custom signal handler. def sigint(*args): reactor.callFromThread(myrepl.keyboard_interrupt) signal.signal(signal.SIGINT, sigint) # Save stdin, stdout and stderr for later restoration orig_stdin = sys.stdin orig_stdout = sys.stdout orig_stderr = sys.stderr # urwid's screen start() and stop() calls currently hit sys.stdin # directly (via RealTerminal.tty_signal_keys), so start the screen # before swapping sys.std*, and swap them back before restoring # the screen. This also avoids crashes if our redirected sys.std* # are called before we get around to starting the mainloop # (urwid raises an exception if we try to draw to the screen # before starting it). def run_with_screen_before_mainloop(): try: # Currently we just set this to None because I do not # expect code hitting stdin to work. For example: exit() # (not sys.exit, site.py's exit) tries to close sys.stdin, # which breaks urwid's shutdown. bpython.cli sets this to # a fake object that reads input through curses and # returns it. When using twisted I do not think we can do # that because sys.stdin.read and friends block, and we # cannot re-enter the reactor. If using urwid's own # mainloop we *might* be able to do something similar and # re-enter its mainloop. sys.stdin = None # FakeStdin(myrepl) sys.stdout = myrepl sys.stderr = myrepl myrepl.main_loop.set_alarm_in(0, start) while True: try: myrepl.main_loop.run() except KeyboardInterrupt: # HACK: if we run under a twisted mainloop this should # never happen: we have a SIGINT handler set. # If we use the urwid select-based loop we just restart # that loop if interrupted, instead of trying to cook # up an equivalent to reactor.callFromThread (which # is what our Twisted sigint handler does) myrepl.main_loop.set_alarm_in( 0, lambda *args: myrepl.keyboard_interrupt()) continue break finally: sys.stdin = orig_stdin sys.stderr = orig_stderr sys.stdout = orig_stdout # This needs more thought. What needs to happen inside the mainloop? def start(main_loop, user_data): if exec_args: bpargs.exec_code(interpreter, exec_args) if not options.interactive: raise urwid.ExitMainLoop() if not exec_args: sys.path.insert(0, "") # this is CLIRepl.startup inlined. filename = os.environ.get("PYTHONSTARTUP") if filename and os.path.isfile(filename): with open(filename) as f: interpreter.runsource(f.read(), filename, "exec") if banner is not None: myrepl.write(banner) myrepl.write("\n") # XXX these deprecation warnings need to go at some point myrepl.write( _("WARNING: You are using `bpython-urwid`, the urwid backend for `bpython`. This backend has been deprecated in version 0.19 and might disappear in a future version." )) myrepl.write("\n") myrepl.start() # This bypasses main_loop.set_alarm_in because we must *not* # hit the draw_screen call (it's unnecessary and slow). def run_find_coroutine(): if find_coroutine(): main_loop.event_loop.alarm(0, run_find_coroutine) run_find_coroutine() myrepl.main_loop.screen.run_wrapper(run_with_screen_before_mainloop) if config.flush_output and not options.quiet: sys.stdout.write(myrepl.getstdout()) if hasattr(sys.stdout, "flush"): sys.stdout.flush() return repl.extract_exit_value(myrepl.exit_value)
def _reactorAction(): return usage.CompleteList( [r.shortName for r in reactors.getReactorTypes()])
def _reactorZshAction(): return "(%s)" % " ".join([r.shortName for r in reactors.getReactorTypes()])
def _reactorAction(): return usage.CompleteList([r.shortName for r in reactors.getReactorTypes()])
def main(args=None, locals_=None, banner=None): translations.init() # TODO: maybe support displays other than raw_display? config, options, exec_args = bpargs.parse(args, ( 'Urwid options', None, [ Option('--twisted', '-T', action='store_true', help=_('Run twisted reactor.')), Option('--reactor', '-r', help=_('Select specific reactor (see --help-reactors). ' 'Implies --twisted.')), Option('--help-reactors', action='store_true', help=_('List available reactors for -r.')), Option('--plugin', '-p', help=_('twistd plugin to run (use twistd for a list). ' 'Use "--" to pass further options to the plugin.')), Option('--server', '-s', type='int', help=_('Port to run an eval server on (forces Twisted).')), ])) if options.help_reactors: try: from twisted.application import reactors # Stolen from twisted.application.app (twistd). for r in reactors.getReactorTypes(): print(' %-4s\t%s' % (r.shortName, r.description)) except ImportError: sys.stderr.write('No reactors are available. Please install ' 'twisted for reactor support.\n') return palette = [ (name, COLORMAP[color.lower()], 'default', 'bold' if color.isupper() else 'default') for name, color in iteritems(config.color_scheme)] palette.extend([ ('bold ' + name, color + ',bold', background, monochrome) for name, color, background, monochrome in palette]) if options.server or options.plugin: options.twisted = True if options.reactor: try: from twisted.application import reactors except ImportError: sys.stderr.write('No reactors are available. Please install ' 'twisted for reactor support.\n') return try: # XXX why does this not just return the reactor it installed? reactor = reactors.installReactor(options.reactor) if reactor is None: from twisted.internet import reactor except reactors.NoSuchReactor: sys.stderr.write('Reactor %s does not exist\n' % ( options.reactor,)) return event_loop = TwistedEventLoop(reactor) elif options.twisted: try: from twisted.internet import reactor except ImportError: sys.stderr.write('No reactors are available. Please install ' 'twisted for reactor support.\n') return event_loop = TwistedEventLoop(reactor) else: # None, not urwid.SelectEventLoop(), to work with # screens that do not support external event loops. event_loop = None # TODO: there is also a glib event loop. Do we want that one? # __main__ construction from bpython.cli if locals_ is None: main_mod = sys.modules['__main__'] = ModuleType('__main__') locals_ = main_mod.__dict__ if options.plugin: try: from twisted import plugin from twisted.application import service except ImportError: sys.stderr.write('No twisted plugins are available. Please install ' 'twisted for twisted plugin support.\n') return for plug in plugin.getPlugins(service.IServiceMaker): if plug.tapname == options.plugin: break else: sys.stderr.write('Plugin %s does not exist\n' % (options.plugin,)) return plugopts = plug.options() plugopts.parseOptions(exec_args) serv = plug.makeService(plugopts) locals_['service'] = serv reactor.callWhenRunning(serv.startService) exec_args = [] interpreter = repl.Interpreter(locals_, locale.getpreferredencoding()) # This nabs sys.stdin/out via urwid.MainLoop myrepl = URWIDRepl(event_loop, palette, interpreter, config) if options.server: factory = EvalFactory(myrepl) reactor.listenTCP(options.server, factory, interface='127.0.0.1') if options.reactor: # Twisted sets a sigInt handler that stops the reactor unless # it sees a different custom signal handler. def sigint(*args): reactor.callFromThread(myrepl.keyboard_interrupt) signal.signal(signal.SIGINT, sigint) # Save stdin, stdout and stderr for later restoration orig_stdin = sys.stdin orig_stdout = sys.stdout orig_stderr = sys.stderr # urwid's screen start() and stop() calls currently hit sys.stdin # directly (via RealTerminal.tty_signal_keys), so start the screen # before swapping sys.std*, and swap them back before restoring # the screen. This also avoids crashes if our redirected sys.std* # are called before we get around to starting the mainloop # (urwid raises an exception if we try to draw to the screen # before starting it). def run_with_screen_before_mainloop(): try: # Currently we just set this to None because I do not # expect code hitting stdin to work. For example: exit() # (not sys.exit, site.py's exit) tries to close sys.stdin, # which breaks urwid's shutdown. bpython.cli sets this to # a fake object that reads input through curses and # returns it. When using twisted I do not think we can do # that because sys.stdin.read and friends block, and we # cannot re-enter the reactor. If using urwid's own # mainloop we *might* be able to do something similar and # re-enter its mainloop. sys.stdin = None #FakeStdin(myrepl) sys.stdout = myrepl sys.stderr = myrepl myrepl.main_loop.set_alarm_in(0, start) while True: try: myrepl.main_loop.run() except KeyboardInterrupt: # HACK: if we run under a twisted mainloop this should # never happen: we have a SIGINT handler set. # If we use the urwid select-based loop we just restart # that loop if interrupted, instead of trying to cook # up an equivalent to reactor.callFromThread (which # is what our Twisted sigint handler does) myrepl.main_loop.set_alarm_in( 0, lambda *args: myrepl.keyboard_interrupt()) continue break finally: sys.stdin = orig_stdin sys.stderr = orig_stderr sys.stdout = orig_stdout # This needs more thought. What needs to happen inside the mainloop? def start(main_loop, user_data): if exec_args: bpargs.exec_code(interpreter, exec_args) if not options.interactive: raise urwid.ExitMainLoop() if not exec_args: sys.path.insert(0, '') # this is CLIRepl.startup inlined. filename = os.environ.get('PYTHONSTARTUP') if filename and os.path.isfile(filename): with open(filename, 'r') as f: if py3: interpreter.runsource(f.read(), filename, 'exec') else: interpreter.runsource(f.read(), filename, 'exec', encode=False) if banner is not None: myrepl.write(banner) myrepl.write('\n') myrepl.start() # This bypasses main_loop.set_alarm_in because we must *not* # hit the draw_screen call (it's unnecessary and slow). def run_find_coroutine(): if find_coroutine(): main_loop.event_loop.alarm(0, run_find_coroutine) run_find_coroutine() myrepl.main_loop.screen.run_wrapper(run_with_screen_before_mainloop) if config.flush_output and not options.quiet: sys.stdout.write(myrepl.getstdout()) if hasattr(sys.stdout, "flush"): sys.stdout.flush() return repl.extract_exit_value(myrepl.exit_value)
def main(args=None, locals_=None, banner=None): translations.init() # TODO: maybe support displays other than raw_display? config, options, exec_args = bpargs.parse(args, ('Urwid options', None, [ Option('--twisted', '-T', action='store_true', help=_('Run twisted reactor.')), Option('--reactor', '-r', help=_('Select specific reactor (see --help-reactors). ' 'Implies --twisted.')), Option('--help-reactors', action='store_true', help=_('List available reactors for -r.')), Option('--plugin', '-p', help=_('twistd plugin to run (use twistd for a list). ' 'Use "--" to pass further options to the plugin.')), Option('--server', '-s', type='int', help=_('Port to run an eval server on (forces Twisted).')), ])) if options.help_reactors: try: from twisted.application import reactors # Stolen from twisted.application.app (twistd). for r in reactors.getReactorTypes(): print(' %-4s\t%s' % (r.shortName, r.description)) except ImportError: sys.stderr.write('No reactors are available. Please install ' 'twisted for reactor support.\n') return palette = [(name, COLORMAP[color.lower()], 'default', 'bold' if color.isupper() else 'default') for name, color in config.color_scheme.items()] palette.extend([('bold ' + name, color + ',bold', background, monochrome) for name, color, background, monochrome in palette]) if options.server or options.plugin: options.twisted = True if options.reactor: try: from twisted.application import reactors except ImportError: sys.stderr.write('No reactors are available. Please install ' 'twisted for reactor support.\n') return try: # XXX why does this not just return the reactor it installed? reactor = reactors.installReactor(options.reactor) if reactor is None: from twisted.internet import reactor except reactors.NoSuchReactor: sys.stderr.write('Reactor %s does not exist\n' % (options.reactor, )) return event_loop = TwistedEventLoop(reactor) elif options.twisted: try: from twisted.internet import reactor except ImportError: sys.stderr.write('No reactors are available. Please install ' 'twisted for reactor support.\n') return event_loop = TwistedEventLoop(reactor) else: # None, not urwid.SelectEventLoop(), to work with # screens that do not support external event loops. event_loop = None # TODO: there is also a glib event loop. Do we want that one? # __main__ construction from bpython.cli if locals_ is None: main_mod = sys.modules['__main__'] = ModuleType('__main__') locals_ = main_mod.__dict__ if options.plugin: try: from twisted import plugin from twisted.application import service except ImportError: sys.stderr.write( 'No twisted plugins are available. Please install ' 'twisted for twisted plugin support.\n') return for plug in plugin.getPlugins(service.IServiceMaker): if plug.tapname == options.plugin: break else: sys.stderr.write('Plugin %s does not exist\n' % (options.plugin, )) return plugopts = plug.options() plugopts.parseOptions(exec_args) serv = plug.makeService(plugopts) locals_['service'] = serv reactor.callWhenRunning(serv.startService) exec_args = [] interpreter = repl.Interpreter(locals_, locale.getpreferredencoding()) # This nabs sys.stdin/out via urwid.MainLoop myrepl = URWIDRepl(event_loop, palette, interpreter, config) if options.server: factory = EvalFactory(myrepl) reactor.listenTCP(options.server, factory, interface='127.0.0.1') if options.reactor: # Twisted sets a sigInt handler that stops the reactor unless # it sees a different custom signal handler. def sigint(*args): reactor.callFromThread(myrepl.keyboard_interrupt) signal.signal(signal.SIGINT, sigint) # Save stdin, stdout and stderr for later restoration orig_stdin = sys.stdin orig_stdout = sys.stdout orig_stderr = sys.stderr # urwid's screen start() and stop() calls currently hit sys.stdin # directly (via RealTerminal.tty_signal_keys), so start the screen # before swapping sys.std*, and swap them back before restoring # the screen. This also avoids crashes if our redirected sys.std* # are called before we get around to starting the mainloop # (urwid raises an exception if we try to draw to the screen # before starting it). def run_with_screen_before_mainloop(): try: # Currently we just set this to None because I do not # expect code hitting stdin to work. For example: exit() # (not sys.exit, site.py's exit) tries to close sys.stdin, # which breaks urwid's shutdown. bpython.cli sets this to # a fake object that reads input through curses and # returns it. When using twisted I do not think we can do # that because sys.stdin.read and friends block, and we # cannot re-enter the reactor. If using urwid's own # mainloop we *might* be able to do something similar and # re-enter its mainloop. sys.stdin = None #FakeStdin(myrepl) sys.stdout = myrepl sys.stderr = myrepl myrepl.main_loop.set_alarm_in(0, start) while True: try: myrepl.main_loop.run() except KeyboardInterrupt: # HACK: if we run under a twisted mainloop this should # never happen: we have a SIGINT handler set. # If we use the urwid select-based loop we just restart # that loop if interrupted, instead of trying to cook # up an equivalent to reactor.callFromThread (which # is what our Twisted sigint handler does) myrepl.main_loop.set_alarm_in( 0, lambda *args: myrepl.keyboard_interrupt()) continue break finally: sys.stdin = orig_stdin sys.stderr = orig_stderr sys.stdout = orig_stdout # This needs more thought. What needs to happen inside the mainloop? def start(main_loop, user_data): if exec_args: bpargs.exec_code(interpreter, exec_args) if not options.interactive: raise urwid.ExitMainLoop() if not exec_args: sys.path.insert(0, '') # this is CLIRepl.startup inlined. filename = os.environ.get('PYTHONSTARTUP') if filename and os.path.isfile(filename): with open(filename, 'r') as f: if py3: interpreter.runsource(f.read(), filename, 'exec') else: interpreter.runsource(f.read(), filename, 'exec', encode=False) if banner is not None: repl.write(banner) repl.write('\n') myrepl.start() # This bypasses main_loop.set_alarm_in because we must *not* # hit the draw_screen call (it's unnecessary and slow). def run_find_coroutine(): if find_coroutine(): main_loop.event_loop.alarm(0, run_find_coroutine) run_find_coroutine() myrepl.main_loop.screen.run_wrapper(run_with_screen_before_mainloop) if config.flush_output and not options.quiet: sys.stdout.write(myrepl.getstdout()) if hasattr(sys.stdout, "flush"): sys.stdout.flush() return repl.extract_exit_value(myrepl.exit_value)
except Exception as e: raise argparse.ArgumentTypeError(e.message) return parse class BooleanAction(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, values if values is not None else True) parser = argparse.ArgumentParser(description='A pure python DNS server serving' ' the content of OpenVPN status files') parser.add_argument('configfile', type=try_parse(ConfigParser.parse_filename), help='file path to configuration file') parser.add_argument('--reactor', choices=sorted(map(lambda r: r.shortName, reactors.getReactorTypes())), help='Select reactor type for twisted') parser.add_argument('--daemon', type=try_parse(ConfigParser.parse_boolean), action=BooleanAction, nargs='?', metavar='BOOL', help='Whether detach and run as daemon') parser.add_argument('--drop-privileges', '--drop', dest='drop', type=try_parse(ConfigParser.parse_boolean), action=BooleanAction, nargs='?', metavar='BOOL', help='Whether drop privileges after opened sockets. User' ' and group information needed (via option or config)') parser.add_argument('--user', type=try_parse(ConfigParser.parse_userid), help='User id or name to use when dropping privileges after' ' opened sockets (see drop-privileges option)') parser.add_argument('--group', type=try_parse(ConfigParser.parse_groupid), help='Group id or name to use when dropping privileges after' ' opened sockets (see drop-privileges option)')