1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

argparseの使い方備忘録

Last updated at Posted at 2022-02-16

業務でPyTorchで実装されたモデルを度々学習させています。ただ、必要なファイルが都度少しずつ異なるという場面が多々有ります。職場の方からargparseを使うと便利だとご教示頂いたので、使ってみるととても使いやすいと感じました。しかし、いつも使い方を忘れてしまうので備忘録メモとして残しておこうと思います。

使用例
class SampleClass

    def __init__(self, required_arg, optional_arg):
        self.required_arg = required_arg
        self.optional_arg = optional_arg

    def sample_func(self):
        pass


if __name__ == "__main__":
    from argparse import ArgumentParser
    arg_parser = ArgumentParser()
    arg_parser.add_argument("required_arg")

    # オプション引数にはデフォルト値も設定
    arg_parser.add_argument("--optional_arg", default=DEFAULT_VALUE)
    args = arg_parser.parse_args()
    
    # デフォルト値を使わない例
    SampleClass(args.required_arg, optional_arg).sample_func()

    # デフォルト値を使う例
    SampleClass(args.required_arg).smaple_func()

Reference

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?