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 whatcheck_output
reads.encoding="utf-8"
hascheck_output
automatically decode the bytes output as UTF-8..splitlines()[0]
splits the output to lines and grabs the first one. If yoursudo
implementation doesn't print the version as the first line, you'd need to adapt that.