LoginSignup
0
0

More than 5 years have passed since last update.

Python 2.7 で 標準入力(stdin)を1行ずつ処理するプログラムのテンプレート

Posted at
echo -e "hoge\nfuge" |python templ.py --format json
{"line": "hoge"}
{"line": "fuge"}

echo -e "hoge\nfuge" |python templ.py --format raw 
hoge
fuge

templ.py

import argparse
import sys
import json

parser = argparse.ArgumentParser(description='hoge')
parser.add_argument('--format', type=str, default="raw", help="output format")
args = vars(parser.parse_args())

type_of_format = args["format"]

while True:
    line = sys.stdin.readline()
    if not line: break
    line = line.rstrip('\r\n')
    if type_of_format == "json":
        _dict = {"line": line}
        print json.dumps(_dict)
    else:
        print line

メモ

for line in fileinput.input():
  print line

だと、args があるとそれをファイルとして読みに行ってしまう。
stdin 強制モードとかあると良いのだが、無いように見える。

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