我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用configargparse.ArgParser()。
def main(): parser = ArgParser(default_config_files=['/etc/factoriomcd.ini', '~/.factoriomcd.ini']) parser.add('-d', '--debug', action='store_true') parser.add('-v', '--verbose', action='store_true') parser.add('--log-file', default="/opt/factorio/server.out") parser.add('--server-id', default="1") parser.add('--rcon-host', default="localhost") parser.add('--rcon-password', default="asdasd") parser.add('--rcon-port', default=31337) parser.add('--ws-url', default="ws://127.0.0.1:8000/ws_v1/server_callback/1/") parser.add('--ws-password', default="asdasd") options = parser.parse_args() if options.verbose: coloredlogs.install(level='DEBUG') logger.debug("FactorioMCd initializing...") else: coloredlogs.install(level='INFO') FactorioMCd(options).run()
def get_args(): default_config = [] if '-cf' not in sys.argv and '--config' not in sys.argv: default_config = [os.getenv('VISION_CONFIG', os.path.join(os.path.dirname(__file__), '../config/config.ini'))] parser = configargparse.ArgParser(default_config_files=default_config, auto_env_var_prefix='VISION_') parser.add_argument("-i", "--image", help="path to image") parser.add_argument("-s", "--sources", type=list, default=[0, 1], help="video sources (default=[0,1])") parser.add_argument("-d", "--display", action="store_true", help="display results of processing in a new window") parser.add_argument("-ip", "--roborio-ip", help="the ip address of the roboRIO") parser.add_argument("-ma", "--min-area", type=int, help="minimum area for blobs") parser.add_argument("-mx", "--max-area", type=int, help="maximum area for blobs") parser.add_argument("-lt", "--lower-color", action="append", nargs="+", type=int, help="lower color threshold for BGR values") parser.add_argument("-ut", "--upper-color", action="append", nargs="+", type=int, help="upper color threshold for BGR values") parser.add_argument("-v", "--verbose", action="store_true", help="for debugging, prints useful values") return vars(parser.parse_args())
def __init__(self,chosen_dir=None): #CMD arguments and configfile if sys.platform == 'win32': self.shell=True par_cmd = os.path.join(sys.path[0],'phpar2.exe') else: self.shell=False par_cmd = 'par2' if chosen_dir == None: parser = ArgParser(default_config_files=['par2deep.ini', '~/.par2deep']) else: parser = ArgParser(default_config_files=[os.path.join(chosen_dir,'par2deep.ini'), '~/.par2deep']) parser.add_argument("-q", "--quiet", action='store_true', help="Don't asks questions, go with all defaults, including repairing and deleting files (default off).") parser.add_argument("-over", "--overwrite", action='store_true', help="Overwrite existing par2 files (default off).") parser.add_argument("-novfy", "--noverify", action='store_true', help="Do not verify existing files (default off).") parser.add_argument("-keep", "--keep_old", action='store_true', help="Keep unused par2 files and old par2 repair files (.1,.2 and so on).") parser.add_argument("-ex", "--excludes", action="append", type=str, default=[], help="Optionally excludes directories ('root' is files in the root of -dir).") parser.add_argument("-exex", "--extexcludes", action="append", type=str, default=[], help="Optionally excludes file extensions.") parser.add_argument("-dir", "--directory", type=str, default=os.getcwd(), help="Path to operate on (default is current directory).") parser.add_argument("-pc", "--percentage", type=int, default=5, help="Set the parity percentage (default 5%%).") parser.add_argument("-pcmd", "--par_cmd", type=str, default=par_cmd, help="Set path to alternative par2 command (default \"par2\").") #lets get a nice dict of all o' that. args = {k:v for k,v in vars(parser.parse_args()).items() if v is not None} self.args = args #add number of files args["nr_parfiles"] = str(1) #number of parity files #set that shit for k,v in self.args.items(): setattr(self, k, v) return
def __init__(self, args, plugins, detect_defaults=False): from certbot import main self.VERBS = {"auth": main.obtain_cert, "certonly": main.obtain_cert, "config_changes": main.config_changes, "run": main.run, "install": main.install, "plugins": main.plugins_cmd, "register": main.register, "renew": main.renew, "revoke": main.revoke, "rollback": main.rollback, "everything": main.run} # List of topics for which additional help can be provided HELP_TOPICS = ["all", "security", "paths", "automation", "testing"] + list(self.VERBS) plugin_names = list(plugins) self.help_topics = HELP_TOPICS + plugin_names + [None] usage, short_usage = usage_strings(plugins) self.parser = configargparse.ArgParser( usage=short_usage, formatter_class=argparse.ArgumentDefaultsHelpFormatter, args_for_setting_config_path=["-c", "--config"], default_config_files=flag_default("config_files")) # This is the only way to turn off overly verbose config flag documentation self.parser._add_config_file_help = False # pylint: disable=protected-access self.detect_defaults = detect_defaults self.args = args self.determine_verb() help1 = self.prescan_for_flag("-h", self.help_topics) help2 = self.prescan_for_flag("--help", self.help_topics) assert max(True, "a") == "a", "Gravity changed direction" self.help_arg = max(help1, help2) if self.help_arg is True: # just --help with no topic; avoid argparse altogether print(usage) sys.exit(0) self.visible_topics = self.determine_help_topics(self.help_arg) self.groups = {} # elements are added by .add_group() self.defaults = {} # elements are added by .parse_args()
def get_arg_parser(self): """Gets the argument parser containing any CLI arguments for the plugin. Note that to avoid argument name conflicts, only long argument names should be used, and they should be prefixed with the plugin-name or unique abbreviation. To get their `ArgParser`, subclasses should call this method via super and capture the returned `ArgParser` instance. Returns: argparse.ArgParser: The `ArgParser` containing the argument definitions. """ return configargparse.ArgParser(add_help=False)
def build_arg_parser(): parser = configargparse.ArgParser(prog='elasticizer', description='from DB to Elasticsearch') parser.add('-c', '--my-config', required=True, is_config_file=True, help='config file path') parser.add('--index', '-i', required=True, dest='index', help='the Elasticsearch index name that Luigi updates') parser.add('--backup_count', '-b', default=0, type=backup_type, dest='backup_count', help=('number of back up indices: creates cycling indices ' '(*-v1 -v2... -vN), with current aliased by the index arg')) parser.add('--table', '-t', required=True, dest='table', help='the name of the SQL table from which Luigi reads') parser.add('--mapping_file', '-m', metavar='mapping file', default='mappings.json', dest='mapping_file', help='the mapping filename used to set up Elasticsearch mappings') parser.add('--settings_file', '-s', metavar='settings file', default='settings.json', dest='settings_file', help='the settings filename used to set up Elasticsearch settings') parser.add('--docs_file', '-o', default='tmp.json', dest='docs_file', help='an output file that stores data being loaded into Elasticsearch.') parser.add('--sql_filter', required=False, default='', dest='sql_filter', help='Filter data from SQL query (e.g. WHERE id is not null)') parser.add('--es_timeout', required=False, default=10, dest='es_timeout', help='timeout when waiting for ES response during indexing') parser.add('--marker_table', action='store_true', default=False, dest='marker_table', help='write to a marker table in the SQL database') parser.add('--restart', '-r', action='store_true', default=False, dest='restart', help='clear all targets before running') parser.add('--clear', action='store_true', default=False, dest='clear', help='clear all targets') return parser
def configure_parser(description, log_params=True): """ Configure an argument parser with some common options and return it. """ parser = ArgParser( description=description, add_config_file_help=False, add_env_var_help=False, default_config_files=[ '/etc/piwheels.conf', '/usr/local/etc/piwheels.conf', '~/.config/piwheels/piwheels.conf' ], ignore_unknown_config_file_keys=True ) parser.add_argument( '--version', action='version', version=__version__) parser.add_argument( '-c', '--configuration', metavar='FILE', default=None, is_config_file=True, help='Specify a configuration file to load') if log_params: parser.set_defaults(log_level=logging.WARNING) parser.add_argument( '-q', '--quiet', dest='log_level', action='store_const', const=logging.ERROR, help='produce less console output') parser.add_argument( '-v', '--verbose', dest='log_level', action='store_const', const=logging.INFO, help='produce more console output') arg = parser.add_argument( '-l', '--log-file', metavar='FILE', help='log messages to the specified file') if argcomplete is not None: arg.completer = argcomplete.FilesCompleter(['*.log', '*.txt']) return parser
def main(): """main""" parser = configargparse.ArgParser( default_config_files=[ os.path.join(CURRENT_DIR, "server.conf"), "server.conf", "/etc/skynet/server.conf"]) parser.add("--debug", dest="debug", default=False, action="store_true") parser.add("--no-debug", dest="debug", action="store_false") parser.add("--log", dest="log", default="") parser.add("--host", dest="host", default=os.environ.get("BIND", "127.0.0.1")) parser.add("--port", dest="port", type=int, default=int(os.environ.get("PORT", 80))) parser.add("--model", dest="model", required=True) parser.add("--gpu", dest="gpu", default=True, action="store_true") parser.add("--no-gpu", dest="gpu", action="store_false") parser.add("--gpu-memory-fraction", type=float, default=0.40, dest="gpu_memory_fraction") config = vars(parser.parse_args()) setup_log(config["log"]) logging.info("config: %s", config) app = App(config) server = httpserver.HTTPServer(app.http_app()) server.bind(config["port"], address=config["host"]) server.start() logging.info("Server Start! Listen: %s", [x.getsockname() for x in server._sockets.values()]) # pylint: disable=protected-access tornado.ioloop.IOLoop.current().start()
def _get_parser(): p = configargparse.ArgParser(default_config_files=CFG_FILES) for (name, dflt, ev, hs) in CFG_DEFAULTS: aname = '--' + name if dflt is False: p.add_argument(aname, default=dflt, action="store_true", env_var=ev, help=hs) else: p.add_argument(aname, default=dflt, env_var=ev, help=hs) return p
def main(): parser = configargparse.ArgParser(description='mergeit hook server') parser.add_argument('-sc', '--server-config', is_config_file=True, help='Server config') parser.add_argument('-H', '--host', type=str, default='*', help='Listen host') parser.add_argument('-p', '--port', type=int, default=1234, help='Listen port') parser.add_argument('-sh', '--shell-host', type=str, default='*', help='Shell listen host') parser.add_argument('-sp', '--shell-port', type=int, default=1235, help='Shell listen port') parser.add_argument('-c', '--config', type=str, help='Config file') parser.add_argument('-l', '--log', type=str, default='/var/log/mergeit', help='Logs dir') args = parser.parse_args() run(args.host, args.port, args.shell_host, args.shell_port, args.config, args.log)
def main(): logging.basicConfig( level=logging.INFO, format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s" ) import configargparse parser = configargparse.ArgParser( default_config_files=CONFIG_FILES, description="Status LED daemon" ) parser.add_argument('-G', '--gpio-pin', default=25, type=int, help='GPIO pin for the LED (default: 25)') args = parser.parse_args() led = None state_map = { "starting": aiy.voicehat.LED.PULSE_QUICK, "ready": aiy.voicehat.LED.BEACON_DARK, "listening": aiy.voicehat.LED.ON, "thinking": aiy.voicehat.LED.PULSE_QUICK, "stopping": aiy.voicehat.LED.PULSE_QUICK, "power-off": aiy.voicehat.LED.OFF, "error": aiy.voicehat.LED.BLINK_3, } try: GPIO.setmode(GPIO.BCM) led = aiy.voicehat.get_led() while True: try: state = input() if not state: continue if state not in state_map: logger.warning("unsupported state: %s, must be one of: %s", state, ",".join(state_map.keys())) continue led.set_state(state_map[state]) except EOFError: time.sleep(1) except KeyboardInterrupt: pass finally: led.stop() GPIO.cleanup()
def main(): parser = configargparse.ArgParser(default_config_files=CONFIG_FILE, config_file_parser_class=configargparse.YAMLConfigFileParser) parser.add('-c', '--config', required=False, is_config_file=True, help='Config file path [DEFAULT: ' + CONFIG_FILE[0] + ']') parser.add('-w', '--web_dir', required=False, default=WEB_DIRECTORY, help='Root of web directory [DEFAULT: ' + WEB_DIRECTORY + ']') parser.add('-d', '--download_dir', required=False, default=DOWNLOAD_DIRECTORY, help='Directory for temporary downloads [DEFAULT: ' + DOWNLOAD_DIRECTORY + ']') parser.add('-t', '--testing', required=False, action='store_true', help='Testing mode (only download a small amount of files) [DEFAULT: ' + str(TESTING) + ']') parser.add('-q', '--quiet', action='store_true', help='Silence console output [DEFAULT: ' + str(QUIET) + ']') parser.add('-g', '--wgrib', required=False, help='Path for wgrib2 [DEFAULT: ' + str(WGRIB) + ']', default=WGRIB) parser.add('-e', '--egrep', required=False, default=EGREP, help='Path for egrep [DEFAULT: ' + str(EGREP) + ']') parser.add('-i', '--imconvert', required=False, default=CONVERT, help='Path for imagemagick Convert [DEFAULT: ' + str(CONVERT) + ']') parser.add('-r', '--maxlat', type=float, required=False, default=MAXLAT, help='Maximum latitude [DEFAULT: ' + str(MAXLAT) + ']') parser.add('-a', '--maxlon', type=float, required=False, default=MAXLON, help='Maximum longitude [DEFAULT: ' + str(MAXLON) + ']') parser.add('-s', '--minlat', type=float, required=False, default=MINLAT, help='Minimum latitude [DEFAULT: ' + str(MINLAT) + ']') parser.add('-f', '--minlon', type=float, required=False, default=MINLON, help='Minimum longitude [DEFAULT: ' + str(MINLON) + ']') # not implemented yet #parser.add('-v', '--variable', required=False, default=VAR, # help='Weather variable to use [DEFAULT: ' + str(VAR) + ']') parser.add('-p', '--threads', type=int, required=False, default=THREAD_MAX, help='Maximum threads to use [DEFAULT: ' + str(THREAD_MAX) + ']') options = parser.parse_args() if find_executable(options.wgrib) is None: print "ERROR: Cannot find wgrib" sys.exit(0) if find_executable(options.imconvert) is None: print "ERROR: Cannot find convert" sys.exit(0) if find_executable(options.egrep) is None: print "ERROR: Cannot find egrep" sys.exit(0) WPEARController.StartRun(options)
def init_config(): p = configargparse.ArgParser(default_config_files=["~/.config/pyLanguagetool.conf"]) p.add_argument("-v", "--verbose", env_var="VERBOSE", default=False, action='store_true') p.add_argument("-a", "--api-url", env_var="API_URL", default="https://languagetool.org/api/v2/") p.add_argument("--no-color", env_var="NO_COLOR", action='store_true', default=False, help="don't color output") p.add_argument("-c", "--clipboard", env_var="CLIPBOARD", action='store_true', default=False, help="get text from system clipboard") p.add_argument("-t", "--input-type", env_var="CLIPBOARD", default="txt", choices=["txt", "html", "md", "rst", "ipynb"], help="if not plaintext") p.add_argument('input file', help='input file', nargs='?') p.add_argument('-l', '--lang', env_var='TEXTLANG', default="auto", help="A language code like en or en-US, or auto to guess the language automatically (see preferredVariants below). For languages with variants (English, German, Portuguese) spell checking will only be activated when you specify the variant, e.g. en-GB instead of just en." ) p.add_argument("-m", "--mother-tongue", env_var="MOTHER__TONGUE", help="A language code of the user's native language, enabling false friends checks for some language pairs." ) p.add_argument("-p", "--preferred-variants", env_var="PREFERRED_VARIANTS", help="Comma-separated list of preferred language variants. The language detector used with language=auto can detect e.g. English, but it cannot decide whether British English or American English is used. Thus this parameter can be used to specify the preferred variants like en-GB and de-AT. Only available with language=auto." ) p.add_argument('-e', '--enabled-rules', env_var='ENABLED_RULES', help='IDs of rules to be enabled, comma-separated') p.add_argument('-d', '--disabled-rules', env_var='DISABLED_RULES', help='IDs of rules to be disabled, comma-separated') p.add_argument('--enabled-categories', env_var='ENABLED_CATEGORIES', help='IDs of categories to be enabled, comma-separated') p.add_argument('--disabled-categories', env_var='DISABLED_CATEGORIES', help='IDs of categories to be disabled, comma-separated') p.add_argument("--enabled-only", action='store_true', default=False, help="enable only the rules and categories whose IDs are specified with --enabled-rules or --enabled-categories" ) c = vars(p.parse_args()) if c["enabled_only"] and (c["disabled_categories"] or c["disabled_rules"]): print("disabled not allowed") # TODO: ? if c["preferred_variants"] and c["lang"] != "auto": # print("You specified --preferred_variants but you didn't specify --language=auto") # sys.exit(2) print('ignoring --preferred-variants as --lang is not set to "auto"') c["preferred_variants"] = None if c["verbose"]: pprint(c) return c
def set_config(root_path): config['ROOT_PATH'] = root_path configpath = get_path('config/config.ini') parser = configargparse.ArgParser(default_config_files=[configpath]) parser.add_argument('-H', '--host', help='Set web server listening host', default='127.0.0.1') parser.add_argument('-P', '--port', type=int, help='Set web server listening port', default=4000) parser.add_argument('-k', '--key', help='Specify a Google Maps API Key to use.') parser.add_argument('-c', '--config', help='Alarms configuration file. default: alarms.json', default='alarms.json') parser.add_argument('-l', '--location', type=parse_unicode, help='Location, can be an address or coordinates') parser.add_argument('-L', '--locale', help='Locale for Pokemon names: default en, check locale folder for more options', default='en') parser.add_argument('-u' , '--units', help='Specify either metric or imperial . Default: metric', choices=['metric', 'imperial'], default='metric') parser.add_argument('-d', '--debug', help='Debug Mode', action='store_true', default=False) parser.add_argument('-gf', '--geofence', help='Specify a file of coordinates, limiting alerts to within this area') parser.add_argument('-tl', '--timelimit', type=int, help='Minimum number of seconds remaining on a pokemon to notify', default=0) parser.add_argument('-tz', '--timezone', help='Timezone used for notifications. Ex: "America/Los_Angeles"') parser.add_argument('-sp', '--sp_url', help='SP_URL') args = parser.parse_args() config['HOST'] = args.host config['PORT'] = args.port config['CONFIG_FILE'] = args.config config['LOCALE'] = args.locale config['DEBUG'] = args.debug config['UNITS'] = args.units config['TIME_LIMIT'] = args.timelimit config['SP_URL'] = args.sp_url if args.key: config['API_KEY'] = key=args.key config['GMAPS_CLIENT'] = googlemaps.Client(key=args.key) if args.location: config['LOCATION'] = get_pos_by_name(args.location) if args.geofence: config['GEOFENCE'] = Geofence(os.path.join(root_path, args.geofence)) if args.timezone: try: config['TIMEZONE'] = pytz.timezone(args.timezone) log.info("Timezone set to: %s" % args.timezone) except pytz.exceptions.UnknownTimeZoneError: log.error("Invalid timezone. For a list of valid timezones, see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones") sys.exit(1) config['REV_LOC'] = False config['DM_WALK'] = False config['DM_BIKE'] = False config['DM_DRIVE'] = False return config #Returns +inf if True, else float, else None
def parse_args(): global args defaultconfigfiles = [] if '-c' not in sys.argv and '--config' not in sys.argv: defaultconfigfiles = ['config.ini'] parser = configargparse.ArgParser( default_config_files=defaultconfigfiles) parser.add_argument('-c', '--config', is_config_file=True, help='Specify configuration file.') parser.add_argument('-hs', '--host', default='127.0.0.1', help='Host or IP to bind to.') parser.add_argument('-p', '--port', type=int, default=4242, help='Port to bind to.') parser.add_argument('-hk', '--hash-key', required=True, action='append', help='Hash key(s) to use.') parser.add_argument('-pf', '--proxies-file', help='Load proxy list from text file (one proxy per line).') parser.add_argument('-l', '--level', type=int, default=30, help='Minimum trainer level required. Lower levels will yield an error.') parser.add_argument('-mqj', '--max-queued-jobs', type=int, default=0, help='Maximum number of queued scout jobs before rejecting new jobs. 0 (default) means no restriction.') parser.add_argument('-mjttl', '--max-job-ttl', type=int, default=0, help='Maximum number of minutes a job is allowed to be queued before it expires (Time-To-Live). ' 'Expired jobs will be rejected when it''s their turn. 0 (default) means no restriction.') parser.add_argument('-sb', '--shadowban-threshold', type=int, default=5, help='Mark an account as shadowbanned after this many errors. ' + 'If --pgpool_url is specified the account gets swapped out.') parser.add_argument('-iv', '--initial-view', default="logs", help=('Initial view. Can be one of "logs", "scouts" or "pokemon". Default is "logs".')) parser.add_argument('-pgpu', '--pgpool-url', help='Address of PGPool to load accounts from and/or update their details.') parser.add_argument('-pgpsid', '--pgpool-system-id', help='System ID for PGPool. Required if --pgpool-url given.') parser.add_argument('-lpf', '--low-prio-file', help='File with Pokemon names or IDs that will be treated with low priority or even dropped.') accs = parser.add_mutually_exclusive_group(required=True) accs.add_argument('-pgpn', '--pgpool-num-accounts', type=int, default=0, help='Use this many accounts from PGPool. --pgpool-url required.') accs.add_argument('-a', '--accounts-file', help='Load accounts from CSV file containing "auth_service,username,passwd" lines.') args = parser.parse_args()