Python twisted.python.usage.UsageError() Examples
The following are 30
code examples of twisted.python.usage.UsageError().
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: cleanup.py From flocker with Apache License 2.0 | 6 votes |
def _yaml_configuration_path_option(option_name, option_value): """ Validate a command line option containing a FilePath to a YAML file. :param unicode option_name: The name of the option being validated. :param unicode option_value: The value being validated. """ yaml_path = _existing_file_path_option(option_name, option_value) try: configuration = yaml.safe_load(yaml_path.open()) except ParserError as e: raise UsageError( u"Problem with --{}. " u"Unable to parse YAML from {}. " u"Error message: {}.".format( option_name, yaml_path.path, unicode(e) ) ) return configuration
Example #2
Source File: trial.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def _checkKnownRunOrder(order): """ Check that the given order is a known test running order. Does nothing else, since looking up the appropriate callable to sort the tests should be done when it actually will be used, as the default argument will not be coerced by this function. @param order: one of the known orders in C{_runOrders} @return: the order unmodified """ if order not in _runOrders: raise usage.UsageError( "--order must be one of: %s. See --help-orders for details" % (", ".join(repr(order) for order in _runOrders),)) return order
Example #3
Source File: cluster_containers_setup.py From flocker with Apache License 2.0 | 6 votes |
def main(reactor, argv, environ): # Setup eliot to print better human-readable output to standard # output eliot_to_stdout(MESSAGE_FORMATS, ACTION_START_FORMATS) options = ContainerOptions() try: options.parseOptions(argv[1:]) except usage.UsageError as e: sys.stderr.write(e.args[0]) sys.stderr.write('\n\n') sys.stderr.write(options.getSynopsis()) sys.stderr.write('\n') sys.stderr.write(options.getUsage()) raise SystemExit(1) container_deployment = ClusterContainerDeployment.from_options(reactor, options) return container_deployment.deploy(options['apps-per-node'])
Example #4
Source File: htmlizer.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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 #5
Source File: tap.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def opt_secondary(self, ip_domain): """Act as secondary for the specified domain, performing zone transfers from the specified IP (IP/domain) """ args = ip_domain.split('/', 1) if len(args) != 2: raise usage.UsageError("Argument must be of the form IP[:port]/domain") address = args[0].split(':') if len(address) == 1: address = (address[0], dns.PORT) else: try: port = int(address[1]) except ValueError: raise usage.UsageError( "Specify an integer port number, not %r" % (address[1],)) address = (address[0], port) self.secondaries.append((address, [args[1]]))
Example #6
Source File: test_tap.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def test_malformedSecondary(self): """ If the value supplied for an I{--secondary} option does not provide a server IP address, optional port number, and domain name, L{Options.parseOptions} raises L{UsageError}. """ options = Options() self.assertRaises( UsageError, options.parseOptions, ['--secondary', '']) self.assertRaises( UsageError, options.parseOptions, ['--secondary', '1.2.3.4']) self.assertRaises( UsageError, options.parseOptions, ['--secondary', '1.2.3.4:hello']) self.assertRaises( UsageError, options.parseOptions, ['--secondary', '1.2.3.4:hello/example.com'])
Example #7
Source File: strcred.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def opt_help_auth_type(self, authType): """ Show help for a particular authentication type. """ try: cf = findCheckerFactory(authType) except InvalidAuthType: raise usage.UsageError("Invalid auth type: %s" % authType) self.authOutput.write("Usage: --auth %s[:ArgString]\n" % authType) self.authOutput.write("ArgString format: %s\n" % cf.argStringFormat) self.authOutput.write('\n') for line in cf.authHelp.strip().splitlines(): self.authOutput.write(' %s\n' % line.rstrip()) self.authOutput.write('\n') if not self.supportsCheckerFactory(cf): self.authOutput.write(' %s\n' % notSupportedWarning) self.authOutput.write('\n') raise SystemExit(0)
Example #8
Source File: tap.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def makeService(config): if not len(config.groups): raise usage.UsageError("No newsgroups specified") db = database.NewsShelf(config['mailhost'], config['datadir']) for (g, m) in config.groups: if m: db.addGroup(g, 'm') db.addModerator(g, m) else: db.addGroup(g, 'y') for s in config.subscriptions: print(s) db.addSubscription(s) s = config['port'] if config['interface']: # Add a warning here s += ':interface='+config['interface'] return strports.service(s, news.UsenetServerFactory(db, config.servers))
Example #9
Source File: tap.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def opt_maildirdbmdomain(self, domain): """ Generate an SMTP/POP3 virtual domain. This option requires an argument of the form 'NAME=PATH' where NAME is the DNS domain name for which email will be accepted and where PATH is a the filesystem path to a Maildir folder. [Example: 'example.com=/tmp/example.com'] """ try: name, path = domain.split('=') except ValueError: raise usage.UsageError("Argument to --maildirdbmdomain must be of the form 'name=path'") self.last_domain = maildir.MaildirDirdbmDomain(self.service, os.path.abspath(path)) self.service.addDomain(name, self.last_domain)
Example #10
Source File: release.py From flocker with Apache License 2.0 | 6 votes |
def initialize_release_main(args, base_path, top_level): """ Clone the Flocker repo and install a new virtual environment for a release. :param list args: The arguments passed to the script. :param FilePath base_path: The executable being run. :param FilePath top_level: The top-level of the flocker repository. """ options = InitializeReleaseOptions() try: options.parseOptions(args) except UsageError as e: sys.stderr.write("%s: %s\n" % (base_path.basename(), e)) raise SystemExit(1) version = options['flocker-version'] path = options['path'] initialize_release(version, path, top_level)
Example #11
Source File: tap.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def opt_aliases(self, filename): """ Specify an aliases(5) file to use for the last specified domain. """ if self.last_domain is not None: if mail.IAliasableDomain.providedBy(self.last_domain): aliases = alias.loadAliasFile(self.service.domains, filename) self.last_domain.setAliasGroup(aliases) self.service.monitor.monitorFile( filename, AliasUpdater(self.service.domains, self.last_domain) ) else: raise usage.UsageError( "%s does not support alias files" % ( self.last_domain.__class__.__name__, ) ) else: raise usage.UsageError("Specify a domain before specifying aliases")
Example #12
Source File: cftp.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def run(): # import hotshot # prof = hotshot.Profile('cftp.prof') # prof.start() args = sys.argv[1:] if '-l' in args: # cvs is an idiot i = args.index('-l') args = args[i:i+2]+args del args[i+2:i+4] options = ClientOptions() try: options.parseOptions(args) except usage.UsageError as u: print('ERROR: %s' % u) sys.exit(1) if options['log']: realout = sys.stdout log.startLogging(sys.stderr) sys.stdout = realout else: log.discardLogs() doConnect(options) reactor.run() # prof.stop() # prof.close()
Example #13
Source File: client.py From flocker with Apache License 2.0 | 6 votes |
def get_steps_pip(distribution, package_source=PackageSource()): """ Get commands to run for testing client pip installation. :param bytes distribution: The distribution the node is running. :param PackageSource package_source: The source from which to install the package. :return: An ``Effect`` to pass to a ``Dispatcher`` that supports ``Sequence``, ``Run``, ``Sudo``, ``Comment``, and ``Put``. """ if distribution not in PIP_DISTRIBUTIONS: raise UsageError( "Distribution %r not supported. Available distributions: %s" % (distribution, ', '.join(PIP_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager virtualenv = 'flocker-client' steps = [ ensure_minimal_setup(package_manager), task_cli_pip_prereqs(package_manager), task_cli_pip_install(virtualenv, package_source), cli_pip_test(virtualenv, package_source), ] return steps
Example #14
Source File: client.py From flocker with Apache License 2.0 | 6 votes |
def get_steps_pkg(distribution, package_source=PackageSource()): """ Get commands to run for testing client package installation. :param bytes distribution: The distribution the node is running. :param PackageSource package_source: The source from which to install the package. :return: An ``Effect`` to pass to a ``Dispatcher`` that supports ``Sequence``, ``Run``, ``Sudo``, ``Comment``, and ``Put``. """ if distribution not in PACKAGED_CLIENT_DISTRIBUTIONS: raise UsageError( "Distribution %r not supported. Available distributions: %s" % (distribution, ', '.join(PACKAGED_CLIENT_DISTRIBUTIONS))) package_manager = DOCKER_IMAGES[distribution].package_manager steps = [ ensure_minimal_setup(package_manager), task_cli_pkg_install(distribution, package_source), ] return steps
Example #15
Source File: _twist.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def options(argv): """ Parse command line options. @param argv: Command line arguments. @type argv: L{list} @return: The parsed options. @rtype: L{TwistOptions} """ options = TwistOptions() try: options.parseOptions(argv[1:]) except UsageError as e: exit(ExitStatus.EX_USAGE, "Error: {}\n\n{}".format(e, options)) return options
Example #16
Source File: client.py From flocker with Apache License 2.0 | 6 votes |
def main(args, base_path, top_level): """ :param list args: The arguments passed to the script. :param FilePath base_path: The executable being run. :param FilePath top_level: The top-level of the Flocker repository. """ options = RunOptions(top_level=top_level) try: options.parseOptions(args) except UsageError as e: sys.exit("%s: %s\n" % (base_path.basename(), e)) distribution = options['distribution'] package_source = options['package_source'] if options['pip']: get_steps = get_steps_pip else: get_steps = get_steps_pkg steps = get_steps(distribution, package_source) container = DockerContainer.from_distribution(distribution) status = run_steps(container, steps) sys.exit(status)
Example #17
Source File: app.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def opt_reactor(self, shortName): """ Which reactor to use (see --help-reactors for a list of possibilities) """ # Actually actually actually install the reactor right at this very # moment, before any other code (for example, a sub-command plugin) # runs and accidentally imports and installs the default reactor. # # This could probably be improved somehow. try: installReactor(shortName) except NoSuchReactor: msg = ("The specified reactor does not exist: '%s'.\n" "See the list of available reactors with " "--help-reactors" % (shortName,)) raise usage.UsageError(msg) except Exception as e: msg = ("The specified reactor cannot be used, failed with error: " "%s.\nSee the list of available reactors with " "--help-reactors" % (e,)) raise usage.UsageError(msg) else: self["reactor"] = shortName
Example #18
Source File: test_application.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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 #19
Source File: test_application.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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 #20
Source File: _images.py From flocker with Apache License 2.0 | 6 votes |
def publish_installer_images_main(reactor, args, base_path, top_level): options = PublishInstallerImagesOptions() try: options.parseOptions(args) except UsageError as e: sys.stderr.write( "Usage Error: %s: %s\n" % ( base_path.basename(), e ) ) raise SystemExit(1) return async_perform( dispatcher=RealPerformers(reactor=reactor).dispatcher(), effect=publish_installer_images_effects(options=options) )
Example #21
Source File: release.py From flocker with Apache License 2.0 | 5 votes |
def parseArgs(self): if self['flocker-version'] is None: raise UsageError("`--flocker-version` must be specified.")
Example #22
Source File: test_usage.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def test_uppercasing(self): """ Error output case adjustment does not mangle options """ opt = WellBehaved() e = self.assertRaises(usage.UsageError, opt.parseOptions, ['-Z']) self.assertEqual(str(e), 'option -Z not recognized')
Example #23
Source File: client.py From flocker with Apache License 2.0 | 5 votes |
def postOptions(self): if self['distribution'] is None: raise UsageError("Distribution required.") self['package_source'] = PackageSource( version=self['flocker-version'], branch=self['branch'], build_server=self['build-server'], )
Example #24
Source File: trial.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def opt_random(self, option): try: self['random'] = long(option) except ValueError: raise usage.UsageError( "Argument to --random must be a positive integer") else: if self['random'] < 0: raise usage.UsageError( "Argument to --random must be a positive integer") elif self['random'] == 0: self['random'] = long(time.time() * 100)
Example #25
Source File: trial.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def opt_recursionlimit(self, arg): """ see sys.setrecursionlimit() """ try: sys.setrecursionlimit(int(arg)) except (TypeError, ValueError): raise usage.UsageError( "argument to recursionlimit must be an integer") else: self["recursionlimit"] = int(arg)
Example #26
Source File: trial.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def opt_tbformat(self, opt): """ Specify the format to display tracebacks with. Valid formats are 'plain', 'emacs', and 'cgitb' which uses the nicely verbose stdlib cgitb.text function """ try: self['tbformat'] = TBFORMAT_MAP[opt] except KeyError: raise usage.UsageError( "tbformat must be 'plain', 'emacs', or 'cgitb'.")
Example #27
Source File: test_twistd.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def test_unimportableConfiguredLogObserver(self): """ C{--logger} with an unimportable module raises a L{UsageError}. """ config = twistd.ServerOptions() e = self.assertRaises( UsageError, config.parseOptions, ['--logger', 'no.such.module.I.hope']) self.assertTrue( e.args[0].startswith( "Logger 'no.such.module.I.hope' could not be imported: " "'no.such.module.I.hope' does not name an object")) self.assertNotIn('\n', e.args[0])
Example #28
Source File: test_twistd.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def test_invalidUmask(self): """ If a value is given for the C{umask} option which cannot be parsed as an integer, L{UsageError} is raised by L{ServerOptions.parseOptions}. """ config = twistd.ServerOptions() self.assertRaises(UsageError, config.parseOptions, ['--umask', 'abcdef'])
Example #29
Source File: test_usage.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def test_tooManyArgumentsAndSpecificErrorMessage(self): """ L{usage.flagFunction} uses the given method name in the error message raised when the method allows too many arguments. """ exc = self.assertRaises( usage.UsageError, usage.flagFunction, self.SomeClass().manyArgs, "flubuduf") self.assertEqual("Invalid Option function for flubuduf", str(exc))
Example #30
Source File: ckeygen.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def run(): options = GeneralOptions() try: options.parseOptions(sys.argv[1:]) except usage.UsageError as u: print('ERROR: %s' % u) options.opt_help() sys.exit(1) log.discardLogs() log.deferr = handleError # HACK if options['type']: if options['type'].lower() in supportedKeyTypes: print('Generating public/private %s key pair.' % (options['type'])) supportedKeyTypes[options['type'].lower()](options) else: sys.exit( 'Key type was %s, must be one of %s' % (options['type'], ', '.join(supportedKeyTypes.keys()))) elif options['fingerprint']: printFingerprint(options) elif options['changepass']: changePassPhrase(options) elif options['showpub']: displayPublicKey(options) else: options.opt_help() sys.exit(1)