0
0

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のノート

Posted at

narg

nargs=*で引数が無い時の挙動が位置引数とオプション引数で違う.

python test.py
parser = argparse.ArgumentParser()
parser.add_argument('infile', nargs='*')
parser.add_argument('-f', '--foo', nargs='*')
args = parser.parse_args()

print(args.infile)
print(args.foo)

引数なしで実行

python3 test.py

[]
None

位置引数は空のリストになるが,オプション引数はNoneになる.

-fだけつけて引数なしの場合

$ python3 test.py

[]
[]

この場合は空のリストになる.

helpをプリントする方法

python test.py
parser = argparse.ArgumentParser()
parser.add_argument('infile', nargs='*')
parser.add_argument('-f', '--foo', nargs='*')
args = parser.parse_args()

parser.print_help()
$ python3 test.py
usage: test.py [-h] [-f [FOO ...]] [infile ...]

positional arguments:
  infile

optional arguments:
  -h, --help            show this help message and exit
  -f [FOO ...], --foo [FOO ...]
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?