LoginSignup
0
1

More than 3 years have passed since last update.

python実行時にオプションを指定する

Posted at

python実行時にオプションを指定するには、ArgumentParserを使う

option_argparser.py
from argparse import ArgumentParser

def get_option(level):
    argparser = ArgumentParser()
    argparser.add_argument('-l', '--level', type=int,
                           default=level,
                           help='Specify level')
    return argparser.parse_args()

level=1
args = get_option(level)

print('level : ' + str(args.level))

実行結果

$ python3 option_argparser.py 
level : 1
$ python3 option_argparser.py -l 3
level : 3
$ python3 option_argparser.py --level 3
level : 3
$ python3 option_argparser.py --help
usage: option_argparser.py [-h] [-l LEVEL]

optional arguments:
  -h, --help            show this help message and exit
  -l LEVEL, --level LEVEL
                        Specify level

参考

argparse --- コマンドラインオプション、引数、サブコマンドのパーサー
ArgumentParserの使い方を簡単にまとめた

0
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
0
1