Python twisted.python.usage.Options() Examples

The following are 30 code examples of twisted.python.usage.Options(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.python.usage , or try the search function .
Example #1
Source File: tap.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _buildResolvers(config):
    """
    Build DNS resolver instances in an order which leaves recursive
    resolving as a last resort.

    @type config: L{Options} instance
    @param config: Parsed command-line configuration

    @return: Two-item tuple of a list of cache resovers and a list of client
        resolvers
    """
    from twisted.names import client, cache, hosts

    ca, cl = [], []
    if config['cache']:
        ca.append(cache.CacheResolver(verbose=config['verbose']))
    if config['hosts-file']:
        cl.append(hosts.Resolver(file=config['hosts-file']))
    if config['recursive']:
        cl.append(client.createResolver(resolvconf=config['resolv-conf']))
    return ca, cl 
Example #2
Source File: test_usage.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_subCommandParseOptionsHasParent(self):
        """
        The parseOptions method from the Options object specified for the
        given subcommand is called.
        """
        class SubOpt(usage.Options):
            def parseOptions(self, *a, **kw):
                self.sawParent = self.parent
                usage.Options.parseOptions(self, *a, **kw)
        class Opt(usage.Options):
            subCommands = [
                ('foo', 'f', SubOpt, 'bar'),
                ]
        o = Opt()
        o.parseOptions(['foo'])
        self.assertTrue(hasattr(o.subOptions, 'sawParent'))
        self.assertEqual(o.subOptions.sawParent , o) 
Example #3
Source File: trial.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def coverdir(self):
        """
        Return a L{FilePath} representing the directory into which coverage
        results should be written.
        """
        coverdir = 'coverage'
        result = FilePath(self['temp-directory']).child(coverdir)
        print("Setting coverage directory to %s." % (result.path,))
        return result


    # TODO: Some of the opt_* methods on this class have docstrings and some do
    #       not. This is mostly because usage.Options's currently will replace
    #       any intended output in optFlags and optParameters with the
    #       docstring. See #6427. When that is fixed, all methods should be
    #       given docstrings (and it should be verified that those with
    #       docstrings already have content suitable for printing as usage
    #       information). 
Example #4
Source File: tap.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def makeService(config):
    """
    Construct a service for operating a SSH server.

    @param config: An L{Options} instance specifying server options, including
        where server keys are stored and what authentication methods to use.

    @return: A L{twisted.application.service.IService} provider which contains
        the requested SSH server.
    """

    t = factory.OpenSSHFactory()

    r = unix.UnixSSHRealm()
    t.portal = portal.Portal(r, config.get('credCheckers', []))
    t.dataRoot = config['data']
    t.moduliRoot = config['moduli'] or config['data']

    port = config['port']
    if config['interface']:
        # Add warning here
        port += ':interface=' + config['interface']
    return strports.service(port, t) 
Example #5
Source File: test_shellcomp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_optMethodsDontOverride(self):
        """
        opt_* methods on Options classes should not override the
        data provided in optFlags or optParameters.
        """
        class Options(usage.Options):
            optFlags = [['flag', 'f', 'A flag']]
            optParameters = [['param', 'p', None, 'A param']]

            def opt_flag(self):
                """ junk description """

            def opt_param(self, param):
                """ junk description """

        opts = Options()
        argGen = _shellcomp.ZshArgumentsGenerator(opts, 'ace', None)

        self.assertEqual(argGen.getDescription('flag'), 'A flag')
        self.assertEqual(argGen.getDescription('param'), 'A param') 
Example #6
Source File: test_shellcomp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_accumulateMetadata(self):
        """
        Are `compData' attributes you can place on Options classes
        picked up correctly?
        """
        opts = FighterAceExtendedOptions()
        ag = _shellcomp.ZshArgumentsGenerator(opts, 'ace', 'dummy_value')

        descriptions = FighterAceOptions.compData.descriptions.copy()
        descriptions.update(FighterAceExtendedOptions.compData.descriptions)

        self.assertEqual(ag.descriptions, descriptions)
        self.assertEqual(ag.multiUse,
                          set(FighterAceOptions.compData.multiUse))
        self.assertEqual(ag.mutuallyExclusive,
                          FighterAceOptions.compData.mutuallyExclusive)

        optActions = FighterAceOptions.compData.optActions.copy()
        optActions.update(FighterAceExtendedOptions.compData.optActions)
        self.assertEqual(ag.optActions, optActions)

        self.assertEqual(ag.extraActions,
                          FighterAceOptions.compData.extraActions) 
Example #7
Source File: _shellcomp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def writeExtras(self):
        """
        Write out completion information for extra arguments appearing on the
        command-line. These are extra positional arguments not associated
        with a named option. That is, the stuff that gets passed to
        Options.parseArgs().

        @return: L{None}

        @raises: ValueError: if C{Completer} with C{repeat=True} is found and
            is not the last item in the C{extraActions} list.
        """
        for i, action in enumerate(self.extraActions):
            # a repeatable action must be the last action in the list
            if action._repeat and i != len(self.extraActions) - 1:
                raise ValueError("Completer with repeat=True must be "
                                 "last item in Options.extraActions")
            self.file.write(
                escape(action._shellCode('', usage._ZSH)).encode('utf-8'))
            self.file.write(b' \\\n') 
Example #8
Source File: _shellcomp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def write(self, genSubs=True):
        """
        Generate the completion function and write it to the output file
        @return: L{None}

        @type genSubs: C{bool}
        @param genSubs: Flag indicating whether or not completions for the list
            of subcommand should be generated. Only has an effect
            if the C{subCommands} attribute has been defined on the
            L{twisted.python.usage.Options} instance.
        """
        if genSubs and getattr(self.options, 'subCommands', None) is not None:
            gen = ZshArgumentsGenerator(self.options, self.cmdName, self.file)
            gen.extraActions.insert(0, SubcommandAction())
            gen.write()
            self.file.write(b'local _zsh_subcmds_array\n_zsh_subcmds_array=(\n')
            for (cmd, short, parser, desc) in self.options.subCommands:
                self.file.write(
                    b'\"' + cmd.encode('utf-8') + b':' + desc.encode('utf-8') +b'\"\n')
            self.file.write(b")\n\n")
            self.file.write(b'_describe "sub-command" _zsh_subcmds_array\n')
        else:
            gen = ZshArgumentsGenerator(self.options, self.cmdName, self.file)
            gen.write() 
Example #9
Source File: test_usage.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_optionsAliasesOrder(self):
        """
        Options which are synonyms to another option are aliases towards the
        longest option name.
        """
        class Opts(usage.Options):
            def opt_very_very_long(self):
                """
                This is an option method with a very long name, that is going to
                be aliased.
                """

            opt_short = opt_very_very_long
            opt_s = opt_very_very_long

        opts = Opts()

        self.assertEqual(
            dict.fromkeys(
                ["s", "short", "very-very-long"], "very-very-long"), {
                "s": opts.synonyms["s"],
                "short": opts.synonyms["short"],
                "very-very-long": opts.synonyms["very-very-long"],
                }) 
Example #10
Source File: _shellcomp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def writeExtras(self):
        """
        Write out completion information for extra arguments appearing on the
        command-line. These are extra positional arguments not associated
        with a named option. That is, the stuff that gets passed to
        Options.parseArgs().

        @return: L{None}

        @raises: ValueError: if C{Completer} with C{repeat=True} is found and
            is not the last item in the C{extraActions} list.
        """
        for i, action in enumerate(self.extraActions):
            # a repeatable action must be the last action in the list
            if action._repeat and i != len(self.extraActions) - 1:
                raise ValueError("Completer with repeat=True must be "
                                 "last item in Options.extraActions")
            self.file.write(
                escape(action._shellCode('', usage._ZSH)).encode('utf-8'))
            self.file.write(b' \\\n') 
Example #11
Source File: test_application.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_reactorSelectionMixinNotAvailable(self):
        """
        Test that the usage mixin exits when trying to use a reactor not
        available (the reactor raises an error at installation), giving an
        error message.
        """
        class ReactorSelectionOptions(usage.Options, app.ReactorSelectionMixin):
            pass
        message = "Missing foo bar"
        def install():
            raise ImportError(message)

        name = 'fakereactortest'
        package = __name__
        description = 'description'
        self.pluginResults = [FakeReactor(install, name, package, description)]

        options = ReactorSelectionOptions()
        options.messageOutput = NativeStringIO()
        e =  self.assertRaises(usage.UsageError, options.parseOptions,
                               ['--reactor', 'fakereactortest', 'subcommand'])
        self.assertIn(message, e.args[0])
        self.assertIn("help-reactors", e.args[0]) 
Example #12
Source File: htmlizer.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def run():
    options = Options()
    try:
        options.parseOptions()
    except usage.UsageError as e:
        print(str(e))
        sys.exit(1)
    filename = options['filename']
    if options.get('stylesheet') is not None:
        stylesheet = styleLink % (options['stylesheet'],)
    else:
        stylesheet = ''

    with open(filename + '.html', 'wb') as output:
        outHeader = (header % {
            'title': filename,
            'generator': 'htmlizer/%s' % (copyright.longversion,),
            'alternate': alternateLink % {'source': filename},
            'stylesheet': stylesheet
            })
        output.write(outHeader.encode("utf-8"))
        with open(filename, 'rb') as f:
            htmlizer.filter(f, output, htmlizer.SmallerHTMLWriter)
        output.write(footer.encode("utf-8")) 
Example #13
Source File: test_usage.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_subCommandInTwoPlaces(self):
        """
        The .parent pointer is correct even when the same Options class is
        used twice.
        """
        class SubOpt(usage.Options):
            pass
        class OptFoo(usage.Options):
            subCommands = [
                ('foo', 'f', SubOpt, 'quux'),
                ]
        class OptBar(usage.Options):
            subCommands = [
                ('bar', 'b', SubOpt, 'quux'),
                ]
        oFoo = OptFoo()
        oFoo.parseOptions(['foo'])
        oBar=OptBar()
        oBar.parseOptions(['bar'])
        self.assertTrue(hasattr(oFoo.subOptions, 'parent'))
        self.assertTrue(hasattr(oBar.subOptions, 'parent'))
        self.failUnlessIdentical(oFoo.subOptions.parent, oFoo)
        self.failUnlessIdentical(oBar.subOptions.parent, oBar) 
Example #14
Source File: tap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _buildResolvers(config):
    """
    Build DNS resolver instances in an order which leaves recursive
    resolving as a last resort.

    @type config: L{Options} instance
    @param config: Parsed command-line configuration

    @return: Two-item tuple of a list of cache resovers and a list of client
        resolvers
    """
    from twisted.names import client, cache, hosts

    ca, cl = [], []
    if config['cache']:
        ca.append(cache.CacheResolver(verbose=config['verbose']))
    if config['hosts-file']:
        cl.append(hosts.Resolver(file=config['hosts-file']))
    if config['recursive']:
        cl.append(client.createResolver(resolvconf=config['resolv-conf']))
    return ca, cl 
Example #15
Source File: test_shellcomp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_accumulateMetadata(self):
        """
        Are `compData' attributes you can place on Options classes
        picked up correctly?
        """
        opts = FighterAceExtendedOptions()
        ag = _shellcomp.ZshArgumentsGenerator(opts, 'ace', BytesIO())

        descriptions = FighterAceOptions.compData.descriptions.copy()
        descriptions.update(FighterAceExtendedOptions.compData.descriptions)

        self.assertEqual(ag.descriptions, descriptions)
        self.assertEqual(ag.multiUse,
                          set(FighterAceOptions.compData.multiUse))
        self.assertEqual(ag.mutuallyExclusive,
                          FighterAceOptions.compData.mutuallyExclusive)

        optActions = FighterAceOptions.compData.optActions.copy()
        optActions.update(FighterAceExtendedOptions.compData.optActions)
        self.assertEqual(ag.optActions, optActions)

        self.assertEqual(ag.extraActions,
                          FighterAceOptions.compData.extraActions) 
Example #16
Source File: test_script.py    From flocker with Apache License 2.0 6 votes vote down vote up
def test_disabled_logging(self):
        """
        If ``logging`` is set to ``False``, ``FlockerScriptRunner.main``
        does not log to ``sys.stdout``.
        """
        class Script(object):
            def main(self, reactor, arguments):
                twisted_log.msg(b"hello!")
                return succeed(None)

        script = Script()
        sys = FakeSysModule(argv=[])
        # XXX: We shouldn't be using this private fake and Twisted probably
        # shouldn't either. See https://twistedmatrix.com/trac/ticket/6200 and
        # https://twistedmatrix.com/trac/ticket/7527
        from twisted.test.test_task import _FakeReactor
        fakeReactor = _FakeReactor()
        runner = FlockerScriptRunner(script, usage.Options(),
                                     reactor=fakeReactor, sys_module=sys,
                                     logging=False)
        self.assertRaises(SystemExit, runner.main)
        self.assertEqual(sys.stdout.getvalue(), b"") 
Example #17
Source File: script.py    From flocker with Apache License 2.0 6 votes vote down vote up
def __init__(self, script, options, logging=True,
                 reactor=None, sys_module=None):
        """
        :param ICommandLineScript script: The script object to be run.
        :param usage.Options options: An option parser object.
        :param logging: If ``True``, log to stdout; otherwise don't log.
        :param reactor: Optional reactor to override default one.
        :param sys_module: An optional ``sys`` like module for use in
            testing. Defaults to ``sys``.
        """
        self.script = script
        self.options = options
        self.logging = logging
        if reactor is None:
            reactor = global_reactor
        self._reactor = reactor

        if sys_module is None:
            sys_module = sys
        self.sys_module = sys_module 
Example #18
Source File: tap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def makeService(config):
    """
    Construct a service for operating a SSH server.

    @param config: An L{Options} instance specifying server options, including
        where server keys are stored and what authentication methods to use.

    @return: A L{twisted.application.service.IService} provider which contains
        the requested SSH server.
    """

    t = factory.OpenSSHFactory()

    r = unix.UnixSSHRealm()
    t.portal = portal.Portal(r, config.get('credCheckers', []))
    t.dataRoot = config['data']
    t.moduliRoot = config['moduli'] or config['data']

    port = config['port']
    if config['interface']:
        # Add warning here
        port += ':interface=' + config['interface']
    return strports.service(port, t) 
Example #19
Source File: test_shellcomp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_incompleteCommandLine(self):
        """
        Completion still happens even if a command-line is given
        that would normally throw UsageError.
        """
        outputFile = BytesIO()
        self.patch(usage.Options, '_shellCompFile', outputFile)
        opts = FighterAceOptions()

        self.assertRaises(SystemExit, opts.parseOptions,
                          ["--fokker", "server", "--unknown-option",
                           "--unknown-option2",
                           "--_shell-completion", "zsh:5"])
        outputFile.seek(0)
        # test that we got some output
        self.assertEqual(1, len(outputFile.read(1))) 
Example #20
Source File: test_usage.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_subCommandParseOptionsHasParent(self):
        """
        The parseOptions method from the Options object specified for the
        given subcommand is called.
        """
        class SubOpt(usage.Options):
            def parseOptions(self, *a, **kw):
                self.sawParent = self.parent
                usage.Options.parseOptions(self, *a, **kw)
        class Opt(usage.Options):
            subCommands = [
                ('foo', 'f', SubOpt, 'bar'),
                ]
        o = Opt()
        o.parseOptions(['foo'])
        self.assertTrue(hasattr(o.subOptions, 'sawParent'))
        self.assertEqual(o.subOptions.sawParent , o) 
Example #21
Source File: test_usage.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_subCommandInTwoPlaces(self):
        """
        The .parent pointer is correct even when the same Options class is
        used twice.
        """
        class SubOpt(usage.Options):
            pass
        class OptFoo(usage.Options):
            subCommands = [
                ('foo', 'f', SubOpt, 'quux'),
                ]
        class OptBar(usage.Options):
            subCommands = [
                ('bar', 'b', SubOpt, 'quux'),
                ]
        oFoo = OptFoo()
        oFoo.parseOptions(['foo'])
        oBar=OptBar()
        oBar.parseOptions(['bar'])
        self.assertTrue(hasattr(oFoo.subOptions, 'parent'))
        self.assertTrue(hasattr(oBar.subOptions, 'parent'))
        self.failUnlessIdentical(oFoo.subOptions.parent, oFoo)
        self.failUnlessIdentical(oBar.subOptions.parent, oBar) 
Example #22
Source File: test_usage.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_optionsAliasesOrder(self):
        """
        Options which are synonyms to another option are aliases towards the
        longest option name.
        """
        class Opts(usage.Options):
            def opt_very_very_long(self):
                """
                This is an option method with a very long name, that is going to
                be aliased.
                """

            opt_short = opt_very_very_long
            opt_s = opt_very_very_long

        opts = Opts()

        self.assertEqual(
            dict.fromkeys(
                ["s", "short", "very-very-long"], "very-very-long"), {
                "s": opts.synonyms["s"],
                "short": opts.synonyms["short"],
                "very-very-long": opts.synonyms["very-very-long"],
                }) 
Example #23
Source File: test_shellcomp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_optMethodsDontOverride(self):
        """
        opt_* methods on Options classes should not override the
        data provided in optFlags or optParameters.
        """
        class Options(usage.Options):
            optFlags = [['flag', 'f', 'A flag']]
            optParameters = [['param', 'p', None, 'A param']]

            def opt_flag(self):
                """ junk description """

            def opt_param(self, param):
                """ junk description """

        opts = Options()
        argGen = _shellcomp.ZshArgumentsGenerator(opts, 'ace', None)

        self.assertEqual(argGen.getDescription('flag'), 'A flag')
        self.assertEqual(argGen.getDescription('param'), 'A param') 
Example #24
Source File: test_application.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_reactorSelectionMixinNonExistent(self):
        """
        Test that the usage mixin exits when trying to use a non existent
        reactor (the name not matching to any reactor), giving an error
        message.
        """
        class ReactorSelectionOptions(usage.Options, app.ReactorSelectionMixin):
            pass
        self.pluginResults = []

        options = ReactorSelectionOptions()
        options.messageOutput = NativeStringIO()
        e = self.assertRaises(usage.UsageError, options.parseOptions,
                              ['--reactor', 'fakereactortest', 'subcommand'])
        self.assertIn("fakereactortest", e.args[0])
        self.assertIn("help-reactors", e.args[0]) 
Example #25
Source File: test_application.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_reactorSelectionMixinNotAvailable(self):
        """
        Test that the usage mixin exits when trying to use a reactor not
        available (the reactor raises an error at installation), giving an
        error message.
        """
        class ReactorSelectionOptions(usage.Options, app.ReactorSelectionMixin):
            pass
        message = "Missing foo bar"
        def install():
            raise ImportError(message)

        name = 'fakereactortest'
        package = __name__
        description = 'description'
        self.pluginResults = [FakeReactor(install, name, package, description)]

        options = ReactorSelectionOptions()
        options.messageOutput = NativeStringIO()
        e =  self.assertRaises(usage.UsageError, options.parseOptions,
                               ['--reactor', 'fakereactortest', 'subcommand'])
        self.assertIn(message, e.args[0])
        self.assertIn("help-reactors", e.args[0]) 
Example #26
Source File: htmlizer.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def run():
    options = Options()
    try:
        options.parseOptions()
    except usage.UsageError as e:
        print(str(e))
        sys.exit(1)
    filename = options['filename']
    if options.get('stylesheet') is not None:
        stylesheet = styleLink % (options['stylesheet'],)
    else:
        stylesheet = ''

    with open(filename + '.html', 'wb') as output:
        outHeader = (header % {
            'title': filename,
            'generator': 'htmlizer/%s' % (copyright.longversion,),
            'alternate': alternateLink % {'source': filename},
            'stylesheet': stylesheet
            })
        output.write(outHeader.encode("utf-8"))
        with open(filename, 'rb') as f:
            htmlizer.filter(f, output, htmlizer.SmallerHTMLWriter)
        output.write(footer.encode("utf-8")) 
Example #27
Source File: trial.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def coverdir(self):
        """
        Return a L{FilePath} representing the directory into which coverage
        results should be written.
        """
        coverdir = 'coverage'
        result = FilePath(self['temp-directory']).child(coverdir)
        print("Setting coverage directory to %s." % (result.path,))
        return result


    # TODO: Some of the opt_* methods on this class have docstrings and some do
    #       not. This is mostly because usage.Options's currently will replace
    #       any intended output in optFlags and optParameters with the
    #       docstring. See #6427. When that is fixed, all methods should be
    #       given docstrings (and it should be verified that those with
    #       docstrings already have content suitable for printing as usage
    #       information). 
Example #28
Source File: test_shellcomp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_brokenActions(self):
        """
        A C{Completer} with repeat=True may only be used as the
        last item in the extraActions list.
        """
        class BrokenActions(usage.Options):
            compData = usage.Completions(
                extraActions=[usage.Completer(repeat=True),
                              usage.Completer()]
                )

        outputFile = BytesIO()
        opts = BrokenActions()
        self.patch(opts, '_shellCompFile', outputFile)
        self.assertRaises(ValueError, opts.parseOptions,
                          ["", "--_shell-completion", "zsh:2"]) 
Example #29
Source File: test_shellcomp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_incompleteCommandLine_case3(self):
        """
        Completion still happens even if a command-line is given
        that would normally throw UsageError.

        Break subcommand detection in a different way by providing
        an invalid subcommand name.
        """
        outputFile = BytesIO()
        self.patch(usage.Options, '_shellCompFile', outputFile)
        opts = FighterAceOptions()

        self.assertRaises(SystemExit, opts.parseOptions,
                          ["--fokker", "unknown-subcommand",
                           "--list-server", "--_shell-completion", "zsh:4"])
        outputFile.seek(0)
        # test that we got some output
        self.assertEqual(1, len(outputFile.read(1))) 
Example #30
Source File: test_shellcomp.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_incompleteCommandLine_case2(self):
        """
        Completion still happens even if a command-line is given
        that would normally throw UsageError.

        The existence of --unknown-option prior to the subcommand
        will break subcommand detection... but we complete anyway
        """
        outputFile = BytesIO()
        self.patch(usage.Options, '_shellCompFile', outputFile)
        opts = FighterAceOptions()

        self.assertRaises(SystemExit, opts.parseOptions,
                          ["--fokker", "--unknown-option", "server",
                           "--list-server", "--_shell-completion", "zsh:5"])
        outputFile.seek(0)
        # test that we got some output
        self.assertEqual(1, len(outputFile.read(1)))

        outputFile.seek(0)
        outputFile.truncate()