How to retrieve useful result from subprocess? [du

2019-09-02 21:43发布

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?

1条回答
Rolldiameter
2楼-- · 2019-09-02 22:06

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'}]
查看更多
登录 后发表回答