2
1

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 3 years have passed since last update.

Python で外部プログラムを実行して結果の行をパースするメモ

Last updated at Posted at 2020-12-16

外部プログラミング実行して結果取得には, 基本 subprocess.run を使います.

subprocessについてより深く(3系,更新版)
https://qiita.com/HidKamiya/items/e192a55371a2961ca8a4

ありがとうございます.

Python には C 言語での scanf 相当が存在しません. regex で頑張るのも面倒です.
{} な記述で scanf 的なのができる parse が便利です.

pip install parse でぺろっと入ります.

外部プログラム実行と結果取得は以下のような感じです.

import subprocess
import parse

def extract_result(lines):
    for line in lines:
        print(line.decode("utf-8"))
        result = parse.parse("ret = {:g}", line.decode("utf-8"))
        if result:
            return result[0]

    raise RuntimeError("`ret = ...` line not found.")


x = 3.13

ret = subprocess.run("python func.py {}".format(str(x)), shell=True, capture_output=True)


lines = ret.stdout.splitlines()

print(extract_result(lines))
# func.py

import sys
import numpy as np

x = float(sys.argv[1])

print("bora")
print("ret = {}".format(np.sin(x)))
print("dora")

shell=True はお好みで(False の場合(デフォルトの場合), シェルの機能(e.g. PATH 変数)使えないので /usr/bin/python などと絶対パス指定が必要)
capture_output で stdout の結果を取得します.

subprocess の stdout の結果は byte 文字列になっているのでデコードが必要です.
通常は utf-8 かと思います.

Convert bytes to a string
https://stackoverflow.com/questions/606191/convert-bytes-to-a-string

TODO

subprocess.run で encoding 指定してもよいかもしれません.

Python の subprocess
https://qiita.com/tanabe13f/items/8d5e4e5350d217dec8f5

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?