LoginSignup
9
6

More than 5 years have passed since last update.

Python でファイルを受け取るコマンドを書くときは argparse の type=open が便利

Last updated at Posted at 2017-11-28

小ネタ。

Python 3 標準モジュールの argparse では、引数を設定する際に type=int のように型を指定できて便利なのだけど、 type=open を指定するとファイルオブジェクトとして引数の値を取得できて、わざわざ open(filepath) する必要がなくなるのでさらに便利。

サンプルコード

filelen.py
#!/usr/bin/env python3

"""ファイルの行数を数えるコマンド"""

import argparse

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('file', type=open, help='テキストファイル')

args = parser.parse_args()

print(len(args.file.readlines()))
$ ./filelen.py -h
usage: filelen.py [-h] file

ファイルの行数を数えるコマンド

positional arguments:
  file        テキストファイル

optional arguments:
  -h, --help  show this help message and exit
$ chmod +x filelen.py
$ ./filelen.py foo.txt
74

任意の関数でも可

type= には1つの文字列を引数に受け取って変換結果を返すような任意の呼び出し可能オブジェクトを渡すことができます

intopen はこれを満たす呼び出し可能オブジェクトなので type= に渡すことができる、ということらしい。

そのため、文字列を任意の値に変換する関数を用意しておいて type= に渡すのでも良い。

9
6
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
9
6