How To Retrieve Useful Result From Subprocess?
Summery With which statement can : b'10.0.3.15' be converted into : '10.0.3.15' What does a b prefix before a python string mean? explains the meaning of 'b' but not answer this
Solution 1:
Use out, _ = p.communicate()
. Then your output is saved as a string in the variable out
. To remove \n
. you can use strip()
(e.g. out.strip()
).
import subprocess
device = 'em1'
cmd = "ip addr show %s | awk '$1 == \"inet\" {gsub(/\/.*$/, \"\", $2); print $2}'" % device
p = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
out, _ = p.communicate()
print(out.strip())
But you should have a look at the Python module netifaces.
import netifaces
device = 'em1'print(netifaces.ifaddresses(device)[netifaces.AF_INET])
This will output something like this:
[{'broadcast': '192.168.23.255', 'netmask': '255.255.255.0', 'addr': '192.168.23.110'}]
Post a Comment for "How To Retrieve Useful Result From Subprocess?"