How to retrieve useful result from subprocess?
Question: # 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?](http://stackoverflow.com/questions/2592764/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 : [Bash parse ifconfig to get only my IP
address](http://stackoverflow.com/questions/23934425/bash-parse-ifconfig-to-
get-only-my-ip-address/23934702#23934702) )

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](https://docs.python.org/3/library/string.html) I see 'b' is a type
which stand for binary.

I only need `'10.0.3.15'`. How to achieve that?


Answer: 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](https://pypi.python.org/pypi/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'}]
    

