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
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.
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'
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.
Note that subprocess.run () can only be used with Python 3.5 or later https://ja.ojit.com/so/python/232121
Recommended Posts