A note that runs an external program in Python and parses the resulting line

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

A note that runs an external program in Python and parses the resulting line
[Python] A program that rounds the score
A python program that resizes a video and turns it into an image
The eval () function that calculates a string as an expression in python
A program that removes duplicate statements in Python
A simple Pub / Sub program note in Python
A script that retrieves tweets with Python, saves them in an external file, and performs morphological analysis.
[Beginner] What happens if I write a program that runs in php in Python?
Note that I understand the least squares algorithm. And I wrote it in Python.
[Python] A program that finds the minimum and maximum values without using methods
[Python] A program that calculates the difference between the total numbers on the diagonal line.
[Python] A program that counts the number of valleys
[Python] A program that compares the positions of kangaroos.
A note on the library implementation that explores hyperparameters using Bayesian optimization in Python
[Python] A program that finds the shortest number of steps in a game that crosses clouds
A Python program in "A book that gently teaches difficult programming"
A general-purpose program that formats Linux command strings in python
[Note] Import of a file in the parent directory in Python
A program that just presses and releases the Esc key
[Python] A program that finds the most common bird types
[C / C ++] Pass the value calculated in C / C ++ to a python function to execute the process, and use that value in C / C ++.
A program that automatically resizes the iOS app icon to the required image size in Python
Summary of points to keep in mind when writing a program that runs on Python 2.5
An easy way to view the time taken in Python and a smarter way to improve it
[Python] A program to find the number of apples and oranges that can be harvested
A Python program that collects tweets containing specific keywords daily and saves them in csv
I made a program in Python that changes the 1-minute data of FX to an arbitrary time frame (1 hour frame, etc.)
Play a sound in Python assuming that the keyboard is a piano keyboard
[Python] Create a program to delete line breaks in the clipboard + Register as a shortcut with windows
python Note: Determine if command line arguments are in the list
I made a program that solves the spot the difference in seconds
I made a Line bot that guesses the gender and age of a person from an image
Easy! Implement a Twitter bot that runs on Heroku in Python
Read the standard output of a subprocess line by line in Python
A function that measures the processing time of a method in python
Understand the probabilities and statistics that can be used for progress management with a python program
[Ev3dev] Create a program that captures the LCD (screen) using python
Read a file in Python with a relative path from the program
Try to write a program that abuses the program and sends 100 emails
A program that determines whether a number entered in Python is a prime number
I tried to find out the difference between A + = B and A = A + B in Python, so make a note
A program that answers a few questions and predicts the next answer
Get the formula in an excel file as a string in Python
[python] A note that started to understand the behavior of matplotlib.pyplot
When writing a program in Python
[Python] A program that rotates the contents of the list to the left
Note that I understand the algorithm of the machine learning naive Bayes classifier. And I wrote it in Python.
[Python / Jupyter] Translate the comment of the program copied to the clipboard and insert it in a new cell
Introducing youtube-dl, a video download tool that runs on the command line, and its zsh completion function.
[Python] A program that calculates the number of chocolate segments that meet the conditions
[Python] A program that calculates the number of socks to be paired
Comparing the basic grammar of Python and Go in an easy-to-understand manner
Open an Excel file in Python and color the map of Japan
I made a program to check the size of a file in Python
A note I looked up to make a command line tool in Python
A useful note when using Python for the first time in a while
How to stop a program in python until a specific date and time
[Python] Note: A self-made function that finds the area of the normal distribution
[Python] A program that creates stairs with #
I made a payroll program in Python!
Write the test in a python docstring