當前位置: 首頁>>代碼示例>>Python>>正文


Python ArgParser.parse_args方法代碼示例

本文整理匯總了Python中configargparse.ArgParser.parse_args方法的典型用法代碼示例。如果您正苦於以下問題:Python ArgParser.parse_args方法的具體用法?Python ArgParser.parse_args怎麽用?Python ArgParser.parse_args使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在configargparse.ArgParser的用法示例。


在下文中一共展示了ArgParser.parse_args方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: create_args

# 需要導入模塊: from configargparse import ArgParser [as 別名]
# 或者: from configargparse.ArgParser import parse_args [as 別名]
def create_args():
    parser = ArgParser()
    parser.add('--db_section')
    parser.add('--reqnums')
    parser.add('--csv')
    args = parser.parse_args()
    return args
開發者ID:DarkEnergySurvey,項目名稱:desdm-dash,代碼行數:9,代碼來源:make_reports.py

示例2: main

# 需要導入模塊: from configargparse import ArgParser [as 別名]
# 或者: from configargparse.ArgParser import parse_args [as 別名]
def main():
    argparser = ArgParser(description="Load TUPA model and visualize, saving to .png file.")
    argparser.add_argument("models", nargs="+", help="model file basename(s) to load")
    args = argparser.parse_args()
    for filename in args.models:
        model = load_model(filename)
        visualize(model, filename)
開發者ID:danielhers,項目名稱:tupa,代碼行數:9,代碼來源:viz.py

示例3: main

# 需要導入模塊: from configargparse import ArgParser [as 別名]
# 或者: from configargparse.ArgParser import parse_args [as 別名]
def main():
    argparser = ArgParser(description="Load TUPA model and save again to a different file.")
    argparser.add_argument("models", nargs="+", help="model file basename(s) to load")
    argparser.add_argument("-s", "--suffix", default=".1", help="filename suffix to append")
    args = argparser.parse_args()
    for filename in args.models:
        model = load_model(filename)
        model.filename += args.suffix
        model.classifier.filename += args.suffix
        model.save()
開發者ID:danielhers,項目名稱:tupa,代碼行數:12,代碼來源:load_save.py

示例4: main

# 需要導入模塊: from configargparse import ArgParser [as 別名]
# 或者: from configargparse.ArgParser import parse_args [as 別名]
def main():
    argparser = ArgParser(description="Visualize scores of a model over the dev set, saving to .png file.")
    argparser.add_argument("models", nargs="+", help="model file basename(s) to load")
    args = argparser.parse_args()
    for pattern in args.models:
        for filename in sorted(glob(pattern)) or [pattern]:
            basename, _ = os.path.splitext(filename)
            for div in "dev", "test":
                try:
                    scores = load_scores(basename, div=div)
                except OSError:
                    continue
                visualize(scores, basename, div=div)
開發者ID:danielhers,項目名稱:tupa,代碼行數:15,代碼來源:visualize_learning_curve.py

示例5: __init__

# 需要導入模塊: from configargparse import ArgParser [as 別名]
# 或者: from configargparse.ArgParser import parse_args [as 別名]
	def __init__(self,chosen_dir=None):
		#CMD arguments and configfile
		if sys.platform == 'win32':
			self.shell=True
			locs = [os.path.join(sys.path[0],'phpar2.exe'),
					'phpar2.exe',
					os.path.join(sys.path[0],'par2.exe'),
					'par2.exe',
					]
			par_cmd = 'par2'
			for p in locs:
				if os.path.isfile(p):
					par_cmd = p
					break
		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
開發者ID:brenthuisman,項目名稱:par2deep,代碼行數:47,代碼來源:par2deep.py

示例6: parse

# 需要導入模塊: from configargparse import ArgParser [as 別名]
# 或者: from configargparse.ArgParser import parse_args [as 別名]
def parse(parser: Parser, args: List[str]) -> Namespace:
    # TODO: accepting a comma-separated list might allow more flexibility
    default_config_file = os.getenv("PYDPIPER_CONFIG_FILE")
    if default_config_file is not None:
      try:
        with open(default_config_file) as _:
          pass
      except:
        warnings.warn(f"PYDPIPER_CONFIG_FILE is set to '{default_config_file}', which can't be opened.")
    config_files = [default_config_file] if default_config_file else []

    # First, build a parser that's aware of all options
    # (will be used for help/version/error messages).
    # This must be tried _before_ the partial parsing attempts
    # in order to get correct help/version messages.

    main_parser = ArgParser(default_config_files=config_files)

    # TODO: abstract out the recursive travels in go_1 and go_2 into a `walk` function
    def go_1(p, current_prefix):
        if isinstance(p, BaseParser):
            g = main_parser.add_argument_group(p.group_name)
            for a in p.argparser._actions:
                new_a = copy.copy(a)
                ss = copy.deepcopy(new_a.option_strings)
                for ix, s in enumerate(new_a.option_strings):
                    if s.startswith("--"):
                        ss[ix] = "-" + current_prefix + "-" + s[2:]  # "" was "-"
                    else:
                        raise NotImplementedError(
                            "sorry, I only understand flags starting with `--` at the moment, but got %s" % s)
                new_a.option_strings = ss
                g._add_action(new_a)
        elif isinstance(p, CompoundParser):
            for q in p.parsers:
                go_1(q.parser, current_prefix + (('-' + q.prefix) if q.prefix is not None else ''))
        else:
            raise TypeError(
                "parser %s wasn't a %s (%s or %s) but a %s" % (p, Parser, BaseParser, CompoundParser, p.__class__))

    go_1(parser, "")

    # Use this parser to exit with a helpful message if parse fails or --help/--version specified:
    main_parser.parse_args(args)

    # Now, use parse_known_args for each parser in the tree of parsers to fill the appropriate namespace object ...
    def go_2(p, current_prefix, current_ns):
        if isinstance(p, BaseParser):
            new_p = ArgParser(default_config_files=config_files)
            for a in p.argparser._actions:
                new_a = copy.copy(a)
                ss = copy.deepcopy(new_a.option_strings)
                for ix, s in enumerate(new_a.option_strings):
                    if s.startswith("--"):
                        ss[ix] = "-" + current_prefix + "-" + s[2:]
                    else:
                        raise NotImplementedError
                    new_a.option_strings = ss
                new_p._add_action(new_a)
            _used_args, _rest = new_p.parse_known_args(args, namespace=current_ns)
            # add a "_flags" field to each object so we know what flags caused a certain option to be set:
            # (however, note that post-parsing we may munge around ...)
            flags_dict = defaultdict(set)
            for action in new_p._actions:
                for opt in action.option_strings:
                    flags_dict[action.dest].add(opt)
            current_ns.flags_ = Namespace(**flags_dict)
            # TODO: could continue parsing from `_rest` instead of original `args`
        elif isinstance(p, CompoundParser):
            current_ns.flags_ = set()  # could also check for the CompoundParser case and not set flags there,
                                       # since there will never be any
            for q in p.parsers:
                ns = Namespace()
                if q.namespace in current_ns.__dict__:
                    raise ValueError("Namespace field '%s' already in use" % q.namespace)
                    # TODO could also allow, say, a None
                else:
                    # gross but how to write n-ary identity fn that behaves sensibly on single arg??
                    current_ns.__dict__[q.namespace] = ns
                    # FIXME this casting doesn't work for configurations with positional arguments,
                    # which aren't unpacked correctly -- better to use a namedtuple
                    # (making all arguments keyword-only also works, but then you have to supply
                    # often meaningless defaults in the __init__)
                go_2(q.parser, current_prefix=current_prefix + (('-' + q.prefix) if q.prefix is not None else ''),
                     current_ns=ns)
                # If a cast function is provided, apply it to the namespace, possibly doing dynamic type checking
                # and also allowing the checker to provide hinting for the types of the fields
                flags = ns.flags_
                del ns.flags_
                fixed = (q.cast(current_ns.__dict__[q.namespace]) #(q.cast(**vars(current_ns.__dict__[q.namespace]))
                                                    if q.cast else current_ns.__dict__[q.namespace])
                if isinstance(fixed, tuple):
                    fixed = fixed.replace(flags_=flags)
                elif isinstance(fixed, Namespace):
                    setattr(fixed, "flags_", flags)
                else:
                    raise ValueError("currently only Namespace and NamedTuple objects are supported return types from "
                                     "parsing; got %s (a %s)" % (fixed, type(fixed)))
                current_ns.__dict__[q.namespace] = fixed
                # TODO current_ns or current_namespace or ns or namespace?
#.........這裏部分代碼省略.........
開發者ID:Mouse-Imaging-Centre,項目名稱:pydpiper,代碼行數:103,代碼來源:arguments.py

示例7: print

# 需要導入模塊: from configargparse import ArgParser [as 別名]
# 或者: from configargparse.ArgParser import parse_args [as 別名]
        if (all([os.path.exists(manifest) for manifest in self.manifests.values()])
                and not self.overwrite):
            print("Found manfiest files, skipping ingest, use --overwrite to overwrite them.")
            return

        for setn, manifest in self.manifests.items():
            pairs = self.train_or_val_pairs(setn)
            records = [(os.path.relpath(fname, self.out_dir), int(tgt))
                       for fname, tgt in pairs]
            records.insert(0, ('@FILE', 'STRING'))
            np.savetxt(manifest, records, fmt='%s\t%s')


if __name__ == "__main__":
    parser = ArgParser()
    parser.add_argument('--input_dir', required=True,
                        help='Directory to find input tars', default=None)
    parser.add_argument('--out_dir', required=True,
                        help='Directory to write ingested files', default=None)
    parser.add_argument('--target_size', type=int, default=256,
                        help='Size in pixels to scale shortest side DOWN to (0 means no scaling)')
    parser.add_argument('--overwrite', action='store_true', default=False, help='Overwrite files')
    args = parser.parse_args()

    logger = logging.getLogger(__name__)

    bw = IngestI1K(input_dir=args.input_dir, out_dir=args.out_dir, target_size=args.target_size,
                   overwrite=args.overwrite)

    bw.run()
開發者ID:StevenLOL,項目名稱:neon,代碼行數:32,代碼來源:ingest.py

示例8: delete_if_exists

# 需要導入模塊: from configargparse import ArgParser [as 別名]
# 或者: from configargparse.ArgParser import parse_args [as 別名]
    if "amr" not in keep:  # Remove AMR-specific features: node label and category
        delete_if_exists((model.feature_params, model.classifier.params), (NODE_LABEL_KEY, "c"))
    delete_if_exists((model.classifier.labels, model.classifier.axes), {NODE_LABEL_KEY}.union(FORMATS).difference(keep))


def delete_if_exists(dicts, keys):
    for d in dicts:
        for key in keys:
            try:
                del d[key]
            except KeyError:
                pass


def main(args):
    os.makedirs(args.out_dir, exist_ok=True)
    for filename in args.models:
        model = load_model(filename)
        strip_multitask(model, args.keep)
        model.filename = os.path.join(args.out_dir, os.path.basename(filename))
        model.save()


if __name__ == "__main__":
    argparser = ArgParser(description="Load TUPA model and save with just one task's features/weights.")
    argparser.add_argument("models", nargs="+", help="model file basename(s) to load")
    argparser.add_argument("-k", "--keep", nargs="+", choices=tuple(filter(None, FORMATS)), default=["ucca"],
                           help="tasks to keep features/weights for")
    argparser.add_argument("-o", "--out-dir", default=".", help="directory to write modified model files to")
    main(argparser.parse_args())
開發者ID:danielhers,項目名稱:tupa,代碼行數:32,代碼來源:strip_multitask.py

示例9: _process_args

# 需要導入模塊: from configargparse import ArgParser [as 別名]
# 或者: from configargparse.ArgParser import parse_args [as 別名]

#.........這裏部分代碼省略.........
        cp_flags.add('--dst-distribution', action='store',
                     help='specify one or more distributions to copy to')
        cp_flags.add('--src-component', action='store', required=True,
                     help='specify one or more components to copy from')
        cp_flags.add('--dst-component', action='store',
                     help='specify one or more components to copy to')
        cp_flags.add('-a', '--architecture', action='append', required=False,
                     help='limit to specified architectures')
        cp_flags.add('-p', '--package', action='append',
                     help='specify one or more package names to act on')
        cp_flags.add('--overwrite',
                     action='store_true', required=False, default=False,
                     help='re-upload packages even if they already exist '
                     'in the repository -- this only applies to cross-'
                     'distribution copies')
        cp_flags.add('--promote',
                     action='store_true', required=False, default=False,
                     help='only copy files where the latest source version '
                     'is more recent than the latest destination version ')
        cp_flags.add('-w', '--wildcard', action='store_true', default=False,
                     help='match package names to left of --package flag')
        cp_latest = cp_flags.add_mutually_exclusive_group()
        cp_latest.add('-v', '--version', action='append',
                      help='only copy packages matching these versions')
        cp_latest.add('-l', '--latest', action='store_const',
                      dest='latest_versions', const=1,
                      help='only copy the most recent package version '
                      '(equivalent to `--recent 1`)')
        cp_latest.add('-r', '--recent', action='store', default=0,
                      type=int, dest='latest_versions',
                      help='only copy the N most recent package versions')
        cp_flags.add('--i-fear-no-evil', action='store_true',
                     default=False, required=False,
                     help='skip confirmation step for scary actions')
        cp_confirm = cp_flags.add_mutually_exclusive_group()
        cp_confirm.add('--confirm', action='store_true', dest='confirm',
                       required=False, default=True,
                       help='confirm any mutating actions')
        cp_confirm.add('-y', '--no-confirm', action='store_false',
                       dest='confirm', required=False, default=False,
                       help='do not prompt for confirmation')

        # remove
        rm_flags.add('-a', '--architecture', action='append', required=False,
                     help='limit to specified architectures')
        rm_flags.add('-d', '--distribution', action='append', required=False,
                     help='limit to specified distributions')
        rm_flags.add('-c', '--component', action='append', required=False,
                     help='limit to specified distributions')
        rm_flags.add('-p', '--package', action='append', required=False,
                     help='limit to specified package names')
        rm_flags.add('--remove-from-s3', action='store_true',
                     default=False, required=False,
                     help='remove package files from s3')
        rm_flags.add('--publish', action='store_true', required=False,
                     default=False, help='publish the repo to s3')
        rm_flags.add('-w', '--wildcard', action='store_true', default=False,
                     help='match package names to left of --package flag')
        rm_flags.add('-H', '--rm-hidden', action='store_true',
                     default=False,
                     help='include packages "hidden" by the removal of '
                     'their distribution/component/architecture')
        rm_flags.add('--i-fear-no-evil', action='store_true',
                     default=False, required=False,
                     help='skip confirmation step for scary actions')
        rm_flags.add('-f', '--format', action='store',
                     dest='outputfmt', default='simple',
                     choices=('json', 'jsonc', 'simple', 'plain', 'grid',
                              'fancy_grid', 'pipe', 'orgtbl', 'jira',
                              'psql', 'rst', 'mediawiki', 'moinmoin',
                              'html', 'latex', 'latex_booktabs', 'textile'),
                     help='select output format for querys & rm/cp prompts')
        rm_latest = rm_flags.add_mutually_exclusive_group()

        rm_latest.add('-v', '--version', action='append',
                      help='only delete packages matching these versions')
        rm_latest.add('-l', '--exclude-latest', action='store_const',
                      dest='latest_versions', const=1,
                      help='only delete the most recent package version '
                      '(equivalent to `--recent 1`)')
        rm_latest.add('-r', '--exclude-recent', action='store', default=0,
                      type=int, dest='latest_versions',
                      help='only delete the N most recent package versions')

        rm_confirm = rm_flags.add_mutually_exclusive_group()
        rm_confirm.add('--confirm', action='store_true', dest='confirm',
                       required=False, default=True,
                       help='confirm any mutating actions')
        rm_confirm.add('-y', '--no-confirm', action='store_false',
                       dest='confirm', required=False, default=False,
                       help='do not prompt for confirmation')

        # publish to s3
        publish_flags.add('-d', '--distribution', action='append',
                          required=False,
                          help='limit to specified distributions '
                               '(default is all)')

        config = flags.parse_args(self.argv)
        return config
開發者ID:memory,項目名稱:repoman,代碼行數:104,代碼來源:config.py


注:本文中的configargparse.ArgParser.parse_args方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。