class SimpleApp(cli.Application): @cli.switch(["a"]) def spam(self): print("!!a") @cli.switch(["b", "bacon"], argtype=int, mandatory=True, envname="PLUMBUM_TEST_BACON") def bacon(self, param): """give me some bacon""" print("!!b", param) eggs = cli.SwitchAttr(["e"], str, help="sets the eggs attribute", envname="PLUMBUM_TEST_EGGS") verbose = cli.CountOf(["v"], help="increases the verbosity level") benedict = cli.CountOf(["--benedict"], help="""a very long help message with lots of useless information that nobody would ever want to read, but heck, we need to test text wrapping in help messages as well""") def main(self, *args): old = self.eggs self.eggs = "lalala" self.eggs = old self.tailargs = args
class BenchBuild(cli.Application): """Frontend for running/building the benchbuild study framework.""" VERSION = settings.CFG["version"].value() _list_env = False verbosity = cli.CountOf('-v', help="Enable verbose output") debug = cli.Flag('-d', help="Enable debugging output") def main(self, *args): self.verbosity = self.verbosity if self.verbosity < 6 else 5 if self.debug: self.verbosity = 3 settings.CFG["verbosity"] = self.verbosity settings.CFG["debug"] = self.debug log.configure() log.set_defaults() if settings.CFG["db"]["create_functions"].value(): from benchbuild.utils.schema import init_functions, Session init_functions(Session()) if args: print("Unknown command {0!r}".format(args[0])) return 1 if not self.nested_command: self.help()
class ConfiguredApplication(cli.Application): 'Application with config' config_filename = cli.SwitchAttr( ['-c', '--config'], argtype=local.path, default=DEFAULT_CONF, argname='CONFIG', help=_("Use file CONFIG for config")) # noqa: Q000 verbose = cli.Flag( ['-v', '--verbose'], help=_("Verbose output - log everything."), # noqa: Q000 excludes=['-s', '--silent']) silence_level = cli.CountOf( ['-s', '--silent'], help=_("Make program more silent"), # noqa: Q000 excludes=['-v', '--verbose']) def main(self): self.config = load_conf(self.config_filename) self.log = logging.getLogger(str(self.__class__).split("'")[1]) self.log.addHandler(logging.StreamHandler()) if self.verbose: self.log.setLevel(logging.DEBUG) else: base_level = logging.INFO self.log.setLevel(base_level + 10 * self.silence_level)
class Container(cli.Application): """Manage uchroot containers.""" VERSION = CFG["version"].value() def __init__(self, exe): super(Container, self).__init__(exe) @cli.switch(["-i", "--input-file"], str, help="Input container path") def input_file(self, container): """Find the input path of a uchroot container.""" p = os.path.abspath(container) if set_input_container(p, CFG): return p = find_hash(CFG["container"]["known"].value(), container) if set_input_container(p, CFG): return raise ValueError("The path '{0}' does not exist.".format(p)) @cli.switch(["-o", "--output-file"], str, help="Output container path") def output_file(self, container): """Find and writes the output path of a chroot container.""" p = os.path.abspath(container) if os.path.exists(p): if not ask("Path '{0}' already exists." " Overwrite?".format(p)): sys.exit(0) CFG["container"]["output"] = p @cli.switch(["-s", "--shell"], str, help="The shell command we invoke inside the container.") def shell(self, custom_shell): """The command to run inside the container.""" CFG["container"]["shell"] = custom_shell @cli.switch(["-t", "-tmp-dir"], cli.ExistingDirectory, help="Temporary directory") def builddir(self, tmpdir): """Set the current builddir of the container.""" CFG["build_dir"] = tmpdir @cli.switch( ["m", "--mount"], cli.ExistingDirectory, list=True, help="Mount the given directory under / inside the uchroot container") def mounts(self, user_mount): """Save the current mount of the container into the settings.""" CFG["container"]["mounts"] = user_mount verbosity = cli.CountOf('-v', help="Enable verbose output") def main(self, *args): log.configure() _log = logging.getLogger() _log.setLevel({ 3: logging.DEBUG, 2: logging.INFO, 1: logging.WARNING, 0: logging.ERROR }[self.verbosity]) update_env() builddir = os.path.abspath(str(CFG["build_dir"].value())) if not os.path.exists(builddir): response = ask("The build directory {dirname} does not exist yet. " "Should I create it?".format(dirname=builddir)) if response: mkdir("-p", builddir) print("Created directory {0}.".format(builddir)) setup_directories(builddir)
class Container(cli.Application): """Manage uchroot containers.""" VERSION = str(CFG["version"]) @cli.switch(["-i", "--input-file"], str, help="Input container path") def input_file(self, _container): """Find the input path of a uchroot container.""" p = local.path(_container) if set_input_container(p, CFG): return p = find_hash(CFG["container"]["known"].value, container) if set_input_container(p, CFG): return raise ValueError("The path '{0}' does not exist.".format(p)) @cli.switch(["-o", "--output-file"], str, help="Output container path") def output_file(self, _container): """Find and writes the output path of a chroot container.""" p = local.path(_container) if p.exists(): if not ui.ask("Path '{0}' already exists." " Overwrite?".format(p)): sys.exit(0) CFG["container"]["output"] = str(p) @cli.switch(["-s", "--shell"], str, help="The shell command we invoke inside the container.") def shell(self, custom_shell): """The command to run inside the container.""" CFG["container"]["shell"] = custom_shell @cli.switch(["-t", "-tmp-dir"], cli.ExistingDirectory, help="Temporary directory") def builddir(self, tmpdir): """Set the current builddir of the container.""" CFG["build_dir"] = tmpdir @cli.switch( ["m", "--mount"], cli.ExistingDirectory, list=True, help="Mount the given directory under / inside the uchroot container") def mounts(self, user_mount): """Save the current mount of the container into the settings.""" CFG["container"]["mounts"] = user_mount verbosity = cli.CountOf('-v', help="Enable verbose output") def main(self, *args): log.configure() builddir = local.path(str(CFG["build_dir"])) if not builddir.exists(): response = ui.ask( "The build directory {dirname} does not exist yet. " "Should I create it?".format(dirname=builddir)) if response: mkdir("-p", builddir) print("Created directory {0}.".format(builddir)) setup_directories(builddir)
class AVDApp(cli.Application): COLOR_MANDATORY = colors.bold & colors.yellow def __init__(self, *args): super().__init__(*args) self.username = "" self.password = "" self.log_filename = None self.lookup = dict() group = "0.0 Lookup file" @cli.switch( "--lookup-file", str, group=group, help= "Liste de fichier lookup à charger. ex: /root/f1.json,/home/test/test.json" ) def lookup_files_load(self, filenames): filenames = filenames.split(',') for filename in filenames: with open(filename, 'r') as lookup_file: self.lookup[os.path.basename(filename).split('.') [0]] = json.load(lookup_file) group = "0.1 Authenfication" @cli.switch(["-u", "--username"], str, group=group, help="Le nom de l'utilisateur") def user(self, username): self.username = username @cli.switch("--password-file", cli.ExistingFile, group=group, requires=["--username"], excludes=["-p", "--password"], help="Le fichier qui permet d'obtenir le mot de passe") def password_file(self, filename): with open(filename, 'r') as passfile: pass_map = json.load(passfile) self.password = '' if not self.username in pass_map.keys( ) else pass_map[self.username] @cli.switch(["-p", "--password"], str, group=group, requires=["--username"], excludes=["--password-file"], help="Le mot de passe en clair ou 'ask' pour obtenir un prompt" ) def get_password(self, password): if password == 'ask': self.password = gp(prompt='Entrer le mot de passe pour user {}: '. format(self.username)) else: self.password = password group = "0.2 Logging" verbosity_level = cli.CountOf( "-v", group=group, help="Donne le niveau de verbosité en comptant le nombre de 'v'") silent_logging = cli.Flag("--silent-logging", default=False, group=group, help="Ne pas afficher les logs vers stdout") @cli.switch(["--log-filename"], str, group=group, help="Log vers un fichier.") def get_log_filename(self, filename): self.log_filename = os.path.expanduser(filename) def main(self): loglevel = lpl.logging.ERROR if self.verbosity_level >= 1: loglevel = lpl.logging.WARNING if self.verbosity_level >= 2: loglevel = lpl.logging.INFO if self.verbosity_level >= 3: loglevel = lpl.logging.DEBUG lpl.init_logger(self.__class__.__name__, to_stream=not self.silent_logging, level=loglevel, to_file=self.log_filename)
class WeekendFare(cli.Application): """Plumbum CLI application: WeekendFare""" # http://plumbum.readthedocs.io/en/latest/cli.html debug = cli.Flag(['d', '--debug'], help='Debug mode, send data to local files') #TODO: debug mode: # -- use local results if possible # -- force user acceptance for hitting API # -- drop debug files # -- toggle global DEBUG option? verbose = cli.Flag(['-v', '--verbose'], help='enable verbose logging') #TODO: add query @cli.switch() calls # -- times to fly between (optional) # -- pasengers (all fields required) pas_adult = cli.CountOf(["-a", "--adult"], help="Adult ticket") pas_child = cli.CountOf(["-c", "--child"], help="Child ticket") pas_infant_lap = cli.CountOf(["-l", "--lap"], help="Infant riding in lap") pas_infant_seat = cli.CountOf(["-i", "--infant"], help="Infant riding in seat") pas_senior = cli.CountOf(["-s", "--senior"], help="Senior ticket") # -- airline (optional) # -- round-trip? def roundtrip(home): if True: return_date = "2016-12-11" early_return_time = "06:00" late_return_time = "22:00" else: return # -- direct flight nonstop = cli.Flag( ["-n", "--nonstop"], help='Nonstop flight', ) layover_wait = 60 # -- refundable? (cli.Flag) refund = cli.Flag(['-r', '--refund'], help='If tickets need to be refundable') #TODO: tryhard mode: multiple "slices" # Use either of the following: # -- repeatable switches: http://plumbum.readthedocs.io/en/latest/cli.html#repeatable-switches # -- sub commands? http://plumbum.readthedocs.io/en/latest/cli.html#sub-commands def main(self): """CLI `main`. Runs core logic of application""" global DEBUG if self.debug: DEBUG = self.debug build_logger(self.verbose) logger.debug('hello world') # -- start city start = cli.terminal.readline( "Origin Airport code:") #make sure is 3-digit str() start.replace('\n', '') start = validate_airport(start) # -- destination city dest = cli.terminal.readline( "End Airport code:") #make sure is 3-digit str() dest.replace('\n', '') dest = validate_airport(dest) # -- travel date(s) date = cli.terminal.readline("Day of flight (YYYY-MM-DD):") date.replace('\n', '') date = validate_datetime(date) qpx_query = {} qpx_query['request'] = {} qpx_query['request']['slice'] = [] #[slice1, slice2, slice3] slice_data = {'origin': start, 'destination': dest, 'date': date} qpx_query['request']['slice'].append(slice_data) qpx_query['request']['pasengers'] = { 'adultCount': self.pas_adult, 'infantInLapCount': self.pas_infant_lap, 'incantInSeatCount': self.pas_infant_seat, 'childCount': self.pas_child, 'seniorCount': self.pas_senior } qpx_query['request'][ 'solutions'] = SOLUTIONS #fixme, make default if not loaded qpx_query['request'][ 'refundable'] = REFUND #fixme, make default if not loaded logger.debug(json.dumps(qpx_query, indent=2))