Use the basic subprocess.run
to execute external programming and get the result.
Deeper about subprocess (3 series, updated version) https://qiita.com/HidKamiya/items/e192a55371a2961ca8a4
Thank you.
There is no C equivalent of scanf in Python. It's also a hassle to work hard with regex.
It is convenient to use parse
, which can be scanf-like with a description of{}
.
https://pypi.org/project/parse/
You can enter it with pip install parse
.
External program execution and result acquisition are as follows.
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
is your choice (if False (default), you cannot use the shell function (e.g. PATH
variable), so you need to specify the absolute path such as / usr/bin/python
)
Get the result of stdout with capture_output
.
The result of stdout of subprocess is a byte string, so decoding is required. I think it's usually utf-8.
Convert bytes to a string https://stackoverflow.com/questions/606191/convert-bytes-to-a-string
TODO
You may specify encoding in subprocess.run
.
Python subprocess https://qiita.com/tanabe13f/items/8d5e4e5350d217dec8f5
Recommended Posts