Store filtered output of cmd command in a variable

  • A+
Category:Languages

I am trying to store the output of a cmd command as a variable in python. To achieve this i am using os.system() but os.system() just runs the process,it doesn't capture the output.

import os   PlatformName = os.system("adb shell getprop | grep -e 'bt.name'") DeviceName = os.system("adb shell getprop | grep -e '.product.brand'") DeviceID = os.system("adb shell getprop | grep -e 'serialno'") Version = os.system("adb shell getprop | grep -e 'version.release'")  print(PlatformName) print(DeviceName) print(DeviceID) print(Version) 

Then i tried to use the subprocess module.

import subprocess import os   PlatformName = subprocess.check_output(["adb shell getprop | grep -e 'bt.name'"]) DeviceName = subprocess.check_output(["adb shell getprop | grep -e '.product.brand'"]) DeviceID = subprocess.check_output(["adb shell getprop | grep -e 'serialno'"]) Version = subprocess.check_output(["adb shell getprop | grep -e 'version.release'"])  print(PlatformName) print(DeviceName) print(DeviceID) print(Version) 

I am getting the following error

FileNotFoundError: [WinError 2] The system cannot find the file specified

How can I store the output of the command as a variable?

 


The issues here:

  • passing arguments like this (string in a list, with spaces) is really not recommended
  • passing arguments like this need shell=True for it to have a slight chance to work, and shell=True is known for security issues (and other issues as well, like non-portability)
  • grep is not standard on windows
  • when not found grep returns 1 and would make check_output fail.

I'd rewrite this:

PlatformName = subprocess.check_output(["adb shell getprop | grep -e 'bt.name'"]) 

as:

output = subprocess.check_output(["adb","shell","getprop"]) platform_name = next((line for line in output.decode().splitlines() if "bt.name" in line),"") 

The second line is a "native" version of grep (without regexes). It returns the first occurrence of "bt.line" in the output lines or empty string if not found. You don't need grep here. And your clients may not have grep installed on Windows.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: