LoginSignup
2
5

More than 5 years have passed since last update.

Python > 実行時引数を指定して実行する > import argparse使用

Last updated at Posted at 2017-03-23
動作環境
Xeon E5-2620 v4 (8コア) x 2
32GB RAM
CentOS 6.8 (64bit)
openmpi-1.8.x86_64 とその-devel
mpich.x86_64 3.1-5.el6とその-devel
gcc version 4.4.7 (とgfortran)
NCAR Command Language Version 6.3.0
WRF v3.7.1を使用。
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) 
Python 3.6.0 on virtualenv

実装中のPython scriptで実行時引数を指定して実行したい。

参考 http://qiita.com/munkhbat1900/items/d7f9b11fb0965085964e
参考 http://qiita.com/petitviolet/items/b8ed39dd6b0a0545dd36

v0.1 > AttributeError: 'Namespace' object has no attribute 't'

上記2つを参考に以下の実装をした。

test_python_170323i.py
import argparse

parser = argparse.ArgumentParser(description = "do something")

parser.add_argument(
    '-t',
    '--timeIndex',
    type = int,
    help = 'time index for netCDF file',
    required = True)

cmd_args = parser.parse_args()

print(cmd_args.t)
$ python test_python_170323i.py -t 314
Traceback (most recent call last):
  File "test_python_170323i.py", line 14, in <module>
    print(cmd_args.t)
AttributeError: 'Namespace' object has no attribute 't'

tというattributeがないとなる。

v0.2 > 成功

test_python_170323i.py
import argparse

parser = argparse.ArgumentParser(description = "do something")

parser.add_argument(
    '-t',
    '--timeIndex',
    type = int,
    help = 'time index for netCDF file',
    required = True)

cmd_args = parser.parse_args()

print(cmd_args.timeIndex)
結果
$ python test_python_170323i.py -t 314
314

--timeIndexを指定する場合は、読出し時に.tでなく.timeIndexを使うということらしい。

https://docs.python.jp/3/library/argparse.html
あたりが関係しそう。

v0.3 > 属性名の指定

destを指定することで属性名を指定できるようだ。

https://docs.python.jp/3/library/argparse.html
の16.4.1.2. 引数を追加する

accumulate 属性はコマンドラインから --sum が指定された場合は

import argparse

parser = argparse.ArgumentParser(description = "do something")

parser.add_argument(
    '-t',
    '--timeIndex',
    dest='time_index',
    type=int,
    help='time index for netCDF file',
    required=True)

cmd_args = parser.parse_args()

print(cmd_args.time_index)

備考

$ python calc_latlon_avg_std_170323.py --timeIndex -20
total: 3477.89
avg_lat: 40.480
avg_lon: 116.246
std_lat: 0.137
std_lon: 0.103
$ python calc_latlon_avg_std_170323.py --timeIndex 4
total: 3477.89
avg_lat: 40.480
avg_lon: 116.246
std_lat: 0.137
std_lon: 0.103

timeIndex指定時に-20を受け入れている。その値は24でラップアラウンドしていて、4を指定した場合と同じ結果になっている。
(timeIndexは実際、[0..23]が指定するようになっている)。

2
5
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
2
5