Home > Net >  How to extract only SUDO version from Linux with python Subprocess
How to extract only SUDO version from Linux with python Subprocess

Time:04-15

I want to extract only the SUDO version from a Linux output. I have command

sudo -V 2>/dev/null| grep "Sudo version" 2>/dev/null

I want to do it with Subprocess I tried some ways but it's not working. As Subprocess takes a list of arguments but I am unable to use it correctly. How can we do it with Subprocess using Python?

CodePudding user response:

Use subprocess.check_output.

>>> import subprocess
>>> subprocess.check_output("sudo --version", shell=True, stderr=subprocess.STDOUT, encoding="utf-8").splitlines()[0]
'Sudo version 1.8.31'
  • The flag shell=True is required to interpret the command line through your shell; otherwise you'd need to do [shutil.which("sudo"), "--version"].
  • stderr=subprocess.STDOUT redirects sudo's stderr output to stdout, which is what check_output reads.
  • encoding="utf-8" has check_output automatically decode the bytes output as UTF-8.
  • .splitlines()[0] splits the output to lines and grabs the first one. If your sudo implementation doesn't print the version as the first line, you'd need to adapt that.
  • Related