0

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?

Community
  • 1
  • 1
Bernard
  • 681
  • 1
  • 8
  • 21

1 Answers1

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'}]
Christian Berendt
  • 3,416
  • 2
  • 13
  • 22
  • The output for me is : b'10.0.3.15' so still with the prefix 'b' – Bernard Jul 02 '14 at 12:55
  • Netifaces looks real powerfull, so I tried to install, according the instruction, but without success. Learned from the past I will not dig into it, to much work with limited results. – Bernard Jul 02 '14 at 13:38