5

why this simple python script not print the real redhat version?

version = os.system( ' cat /etc/redhat-release  | awk \'{print $7}\' '  )
print ("my version is " ,version)

when I run it

we got:

7.2
('my version is ', 0)
  1. why we get 0 instead 7.2?
  2. how to avoid to get version - 7.2 from os.system ?
ilkkachu
  • 138,973
jango
  • 423

3 Answers3

14

os.system() just runs the process, it doesn't capture the output:

If command generates any output, it will be sent to the interpreter standard output stream.

The return value is the exit code of the process:

On Unix, the return value is the exit status of the process encoded in the format specified for wait().

You'll need to use something like subprocess.check_output() or subprocess.Popen() directly to capture the output.

>>> arch = subprocess.check_output("uname -a | awk '{print $9}'", shell=True);
>>> arch
'x86_64\n'
ilkkachu
  • 138,973
2

You can use subprocess module and achieve this fairly easy.

#!/usr/bin/python3

import subprocess
getVersion =  subprocess.Popen("awk '{print $7}' /etc/redhat-release", shell=True, stdout=subprocess.PIPE).stdout
version =  getVersion.read()

print("My version is", version.decode())

Also for the awk part, you can use sed 's/[^0-9_.-]//g /etc/redhat-release. This will only extract the version number and doesn't need to know what field version number is which makes it more platform independant.

-1

For example, you can do:

os.system("ping 1.1.1.1 >> ping.txt")
with open("ping.txt", "r") as ping:
    print(ping.read())
Alon
  • 101
  • 4
    This has several issues. First of all, it is needlessly creating a temp file. Second, you are appending to the tmp file, so if it already exists you will have extra data. Finally, ping is a very bad example since it will never finish so your code will simply hang. – terdon Feb 18 '21 at 12:30