Notebook

これは日々の作業を通して学んだことや毎日の生活で気づいたことをを記録しておく備忘録である。

HTML ファイル生成日時: 2024/05/08 09:31:52.302 (台灣標準時)

Python での argparse を使ったコマンドライン引数の取り扱い方法

Python では、 argparse モジュールを使うと、簡便にコマンドライン引数を 取り扱うことができる。

簡単な optional argument の例

以下に、 argparse を使った簡単な optional argument の使用例を示す。 argparse.ArgumentParser でparser を生成し、 add_argument で引数を追加 し、 parse_args で引数を解析する。 default を使うと、そのオプションが 明示的に指定されなかったときの引数の値を設定することができる。

#!/usr/pkg/bin/python3.9

# importing argparse module
import argparse

# initialising a parser
parser = argparse.ArgumentParser (description='adding two integers')

# adding arguments
parser.add_argument ('-a', type=int, default=0, help='integer 1')
parser.add_argument ('-b', type=int, default=0, help='integer 2')

# parsing arguments
args = parser.parse_args ()

# printing arguments
print ("args =", args)

# two numbers
a = args.a
b = args.b

# printing a and b
print ("a =", a)
print ("b =", b)

# calculation
c = a + b

# printing result
print ("c =", c)

実際に、実行してみると、以下のようになる。
% ./test_argparse_0.py -h
usage: test_argparse_0.py [-h] [-a A] [-b B]

adding two integers

optional arguments:
  -h, --help  show this help message and exit
  -a A        integer 1
  -b B        integer 2

% ./test_argparse_0.py -a 2 -b 3
args = Namespace(a=2, b=3)
a = 2
b = 3
c = 5
引数は整数でなければならないので、浮動小数点を与えるとエラーとなる。
% ./test_argparse_0.py -a 2.0 -b 3.0
usage: test_argparse_0.py [-h] [-a A] [-b B]
test_argparse_0.py: error: argument -a: invalid int value: '2.0'

引数が浮動小数点だと指定する

type で float を指定すれば、引数は浮動小数点でなければならなくなる。

#!/usr/pkg/bin/python3.9

# importing argparse module
import argparse

# initialising a parser
parser = argparse.ArgumentParser (description='adding two floats')

# adding arguments
parser.add_argument ('-a', type=float, default=0.0, help='float 1')
parser.add_argument ('-b', type=float, default=0.0, help='float 2')

# parsing arguments
args = parser.parse_args ()

# printing arguments
print ("args =", args)

# two numbers
a = args.a
b = args.b

# printing a and b
print ("a =", a)
print ("b =", b)

# calculation
c = a + b

# printing result
print ("c =", c)

実行してみる。
% ./test_argparse_1.py -h
usage: test_argparse_1.py [-h] [-a A] [-b B]

adding two floats

optional arguments:
  -h, --help  show this help message and exit
  -a A        float 1
  -b B        float 2

% ./test_argparse_1.py -a 1.2 -b 3.4
args = Namespace(a=1.2, b=3.4)
a = 1.2
b = 3.4
c = 4.6

positional argument の例

argparse を使って positional argument を利用してみる。 nargs を使うと、 引数の数を指定することができる。

#!/usr/pkg/bin/python3.9

# importing argparse module
import argparse

# initialising a parser
parser = argparse.ArgumentParser (description='processing files')

# adding arguments
parser.add_argument ('files', nargs='+', help='FITS files')

# parsing arguments
args = parser.parse_args ()

# printing arguments
print ("args =", args)

# FITS files
files = args.files

# printing file names
print ("list of files:")
for file in files:
    print ("  ", file)

実行してみる。
% ./test_argparse_2.py -h
usage: test_argparse_2.py [-h] files [files ...]

processing files

positional arguments:
  files       FITS files

optional arguments:
  -h, --help  show this help message and exit

% ./test_argparse_2.py a.fits b.fits c.fits
args = Namespace(files=['a.fits', 'b.fits', 'c.fits'])
list of files:
   a.fits
   b.fits
   c.fits

choices を使って与えられたリストから選ぶオプション

choices を使うと、与えられたリストの中からどれかを選ぶというオプション を用意することができる。

#!/usr/pkg/bin/python3.9

# importing argparse module
import argparse

# initialising a parser
parser = argparse.ArgumentParser (description='arithmetic operation')

# adding arguments
parser.add_argument ('file1', nargs=1, default='a.fits', help='FITS file 1')
parser.add_argument ('op', choices=['+', '-', 'x', '/'],
                     default='+', help='arithmetic operator')
parser.add_argument ('file2', nargs=1, default='b.fits', help='FITS file 2')
parser.add_argument ('file3', nargs=1, default='c.fits', help='FITS file 3')

# parsing arguments
args = parser.parse_args ()

# printing arguments
print ("args =", args)

# FITS files
file1 = args.file1[0]
op    = args.op
file2 = args.file2[0]
file3 = args.file3[0]

# printing command
print ("command:", file1, op, file2, "-->", file3)

実行してみる。
% ./test_argparse_3.py -h
usage: test_argparse_3.py [-h] file1 {+,-,x,/} file2 file3

arithmetic operation

positional arguments:
  file1       FITS file 1
  {+,-,x,/}   arithmetic operator
  file2       FITS file 2
  file3       FITS file 3

optional arguments:
  -h, --help  show this help message and exit

% ./test_argparse_3.py raw.fits - bias.fits red.fits
args = Namespace(file1=['raw.fits'], op='-', file2=['bias.fits'], file3=['red.fits'])
command: raw.fits - bias.fits --> red.fits

long option を使う

以下のようにすれば、 long option を使うことができる。

#!/usr/pkg/bin/python3.9

# importing argparse module
import argparse

# initialising a parser
parser = argparse.ArgumentParser (description='long option')

# adding arguments
parser.add_argument ('-o', '--output', default='out.fits', help='output file')
parser.add_argument ('files', nargs='+', help='input files')

# parsing arguments
args = parser.parse_args ()

# printing arguments
print ("args =", args)

# FITS files
file_output = args.output
files_input = args.files

# printing input parameters
print ("output file:", file_output)
print ("input files:")
for file in files_input:
    print ("  ", file)

実行してみる。
% ./test_argparse_4.py -h
usage: test_argparse_4.py [-h] [-o OUTPUT] files [files ...]

long option

positional arguments:
  files                 input files

optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                        output file

% ./test_argparse_4.py --output out.fits a.fits b.fits c.fits d.fits e.fits
args = Namespace(output='out.fits', files=['a.fits', 'b.fits', 'c.fits', 'd.fits', 'e.fits'])
output file: out.fits
input files:
   a.fits
   b.fits
   c.fits
   d.fits
   e.fits

参考文献



Frequently accessed files

  1. Computer___Python/20220518_0.html
  2. Computer___FreeBSD/20220621_0.html
  3. Food___Taiwan/20220429_0.html
  4. Computer___Network/20230516_00.html
  5. Computer___Python/20220715_0.html
  6. Computer___NetBSD/20220817_3.html
  7. Computer___Python/20220410_0.html
  8. Computer___Debian/20210223_1.html
  9. Food___Taiwan/20230526_00.html
  10. Food___Taiwan/20210205_5.html
  11. Computer___Python/20210124_0.html
  12. Computer___Network/20230508_00.html
  13. Computer___NetBSD/20220818_1.html
  14. Food___Taiwan/20210205_1.html
  15. Computer___NetBSD/20220428_0.html
  16. Science___Astronomy/20220503_0.html
  17. Computer___TeX/20230503_00.html
  18. Travel___Taiwan/20220809_2.html
  19. Computer___NetBSD/20210204_0.html
  20. Computer___Network/20230726_00.html
  21. Science___Math/20220420_0.html
  22. Computer___NetBSD/20230515_00.html
  23. Science___Astronomy/20220420_1.html
  24. Computer___NetBSD/20220808_0.html
  25. Computer___NetBSD/20230119_00.html
  26. Food___Taiwan/20230618_00.html
  27. Computer___Python/20220816_1.html
  28. Food___Taiwan/20220424_8.html
  29. Food___Taiwan/20220424_1.html
  30. Computer___NetBSD/20210204_2.html


HTML file generated by Kinoshita Daisuke.