This question already has an answer here:
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 question.
An working answer on this question will be of course voted as solved.
Full
From shell can find my IP address with the complex statement :
ip addr show eth0 | awk '$1 == "inet" {gsub(/\/.*$/, "", $2); print $2}'
(source : Parse ifconfig to get only my IP address using Bash )
Which returns for me: 10.0.3.15
That is Ok.
Now I want this statement, or any statement, to be executed in Python. Because the statement has all kind of specific tokens, I just write to file, and read the file into variable cmd
I checked the content of cmd
is identical to the above statement. Now I execute this command in Python :
p = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
b = p.communicate()
The result is a tuple, I only need the content:
value = b[0]
The value is b'10.0.3.15\\n'
In Format Specification Mini Language I see 'b' is a type which stand for binary.
I only need '10.0.3.15'
. How to achieve that?
Use
out, _ = p.communicate()
. Then your output is saved as a string in the variableout
. To remove\n
. you can usestrip()
(e.g.out.strip()
).But you should have a look at the Python module netifaces.
This will output something like this: