Python Forum

Full Version: Command output to Variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Good afternoon everyone. I am new to python and I am trying to get my self up to speed as soon as possible. I thought it would be easy since ive already worked with VBS and Powershell but this seems like a whole new animal. so what I am trying to do is i want to run a command in shell then take the output of that command and load it onto a variable. I then want to take the output and do a for each loop so i can add an additional if statement to look for specific syntax and weed out what i want from what i dont. however each time i have tried it i cant find a way to read one line at a time it just gives me the entire output so i am not sure what im doing wrong. it is possible that the tool I am using to generate the output is at fault but i dont se how yet. any assistance you can provide would be greatly appreciated. below is one of the pieces of code ive used that partially succeeds. just fyi the msecli -L command is a Micron tool used to gather Nvme HDD status info. this is the data i am trying to collect.

import time
import sys
import subprocess
#subprocess.call('msecli -L', shell=true)
proc=subprocess.Popen('msecli -L', shell=True, stdout=subprocess.PIPE, )
output=proc.communicate()[0]
print(output)


driveoutputA = [ str(output, 'utf-8') ]

print(driveoutputA)


for val in str(driveoutputA, 'utf-8'): 

print(val, end=' ')

time.sleep(3) # Sleep for 3 seco
The output is just the STDOUT as a str. If you want to treat it as lines, just split on newlines. Also, it will be returned as bytes, so decoding it back to str is often appropriate.

I would probably use .run() instead, but that's minor. The code above would work just fine once the output is split.
import subprocess

cmd = "/bin/ls"
p = subprocess.run(cmd, capture_output=True)
lines = p.stdout.decode().splitlines()
print(f"{cmd} output contained {len(lines)} lines")
# loop over lines
# for line in lines....
Alternatively, you can use check_output(), which will convert to a str itself.

import subprocess

cmd = "/bin/ls"
output = subprocess.check_output(cmd)
lines = output.splitlines()
print(f"{cmd} output contained {len(lines)} lines")