[Mac] A super-easy way to execute system commands in Python and output the results

This time, I will explain how to execute system commands in Python, which everyone loves, and output the results. It's called a system command, but it's a way to execute all the commands that can be used on Terminal in Python.

How to get only download and upload from Speedtest json using jq https://qiita.com/Bob_Alice/items/83c0686f56012b300780

Use the Python library "subprocess"

First of all, you can easily execute system commands by using the Python library "subprocess".

It's super easy to use, in Python

result = subprocess.run(['command','そのcommandの引数'], stdout=subprocess.PIPE)

Then

result.returncode

The status code (success or failure) of the command is entered in

result.stdout

The standard output result is assigned to.

What to do if there are multiple arguments

When there are multiple arguments, there seems to be various ways, but there seems to be a security problem. This time, the command to be used and its arguments were decided for my use, so I made a shell script to execute it. A shell script is not difficult, it just saves a file with the command and arguments you want to use with the extension .sh. This time, the purpose was to execute the following command that outputs a specific value using the jq command from the prepared json file.

cat result.json | jq ".download.bandwidth"

Therefore, I wrote this command in a file called "get_download_bandwidth_from_result.sh" and saved it.

Then it became the following Python code.

import subprocess

result = subprocess.run(['sh','get_download_bandwidth_from_result.sh'], stdout=subprocess.PIPE)
print(result.returncode)
print(result.stdout)

Output result

b'33052461\n'

I have to decode the characters

However, when the standard output is received by the subprocess, it will be an encoded byte. You need to decode it to get it to look normal.

Deeper about subprocess (3 series, updated version) https://qiita.com/HidKamiya/items/e192a55371a2961ca8a4

Therefore

result.stdout.decode().strip().split('\n')

By doing so, I was able to decourse.

However, since the decourse result is stored as a list, it is necessary to specify that it is the first (0th) variable in the list in order to treat it as a single variable.

output = result.stdout.decode().strip().split('\n')[0]

By doing so, the variable output contains the first number after decourse.

The end result is the following Python code.

import subprocess

result = subprocess.run(['sh','get_download_bandwidth_from_result.sh'], stdout=subprocess.PIPE)
print(result.returncode)
print(result.stdout)
print(result.stdout.decode().strip().split('\n'))

This is perfect. The end.

Postscript

Note that subprocess.run () can only be used with Python 3.5 or later https://ja.ojit.com/so/python/232121

Recommended Posts

[Mac] A super-easy way to execute system commands in Python and output the results
A standard way to develop and distribute packages in Python
How to execute external shell scripts and commands in python
It is easy to execute SQL with Python and output the result in Excel
[C / C ++] Pass the value calculated in C / C ++ to a python function to execute the process, and use that value in C / C ++.
An easy way to view the time taken in Python and a smarter way to improve it
How to display bytes in the same way in Java and Python
What is the fastest way to create a reverse dictionary in python?
A clever way to time processing in Python
Output in the form of a python array
[Python] How to save the installed package and install it in a new environment at once Mac environment
How to input a character string in Python and output it as it is or in the opposite direction.
How to count the number of elements in Django and output to a template
Execute external commands in python (both receiving/not receiving results)
How to execute a command using subprocess in Python
Output a binary dump in binary and revert to a binary file
[Python] How to output the list values in order
Run the output code with tkinter, saying "A, pretending to be B" in python
How to execute a schedule by specifying the Python time zone and execution frequency
[Python] Change the text color and background color of a specific keyword in print output
Save the pystan model and results in a pickle file
Output "Draw ferns programmatically" to the drawing process in Python
How to use the __call__ method in a Python class
Probably the easiest way to create a pdf with Python3
Sort and output the elements in the list as elements and multiples in Python.
A simple way to avoid multiple for loops in Python
Build a Python environment and transfer data to the server
How to get the last (last) value in a list in Python
Introducing a good way to manage DB connections in Python
Just try to receive a webhook in ngrok and python
How to start the PC at a fixed time every morning and execute the python program
Recursively get the Excel list in a specific folder with python and write it to Excel.
Seeking a unified way to wait and get for state changes in Selenium for Python elements
I also tried to imitate the function monad and State monad with a generator in Python
Output the key list included in S3 Bucket to a file
Determine the date and time format in Python and convert to Unixtime
Run the output code on the local web server as "A, pretending to be B" in python
How to determine the existence of a selenium element in Python
Write a script in Shell and Python to notify you in Slack when the process is finished
Hit the echo command in the Mac terminal to output Hello World
[Introduction to Python] How to output a character string in a Print statement
Output the contents of ~ .xlsx in the folder to HTML with Python
Read the standard output of a subprocess line by line in Python
In the python command python points to python3.8
[Introduction to Python] How to use the in operator in a for statement?
How to check the memory size of a dictionary in Python
I tried to find out the difference between A + = B and A = A + B in Python, so make a note
[Python] The role of the asterisk in front of the variable. Divide the input value and assign it to a variable
Export and output files in Python
[Python scraping] Output the URL and title of the site containing a specific keyword to a text file
Get the list in the S3 bucket with Python and search with a specific Key. Output the Key name, last update date, and count number to a file.
[Python / Jupyter] Translate the comment of the program copied to the clipboard and insert it in a new cell
Easy way to enter and execute AtCoder test cases in Jupyter Notebook
[Introduction to Python] What is the difference between a list and a tuple?
How to write the correct shebang in Perl, Python and Ruby scripts
How to get the date and time difference in seconds with python
[Linux] Command to get a list of commands executed in the past
How to put a half-width space before letters and numbers in Python.
Sample code to get the Twitter API oauth_token and oauth_token_secret in Python 2.7
Connect to postgreSQL from Python and use stored procedures in a loop.
Get and convert the current time in the system local timezone with python