如何从子有用的结果? [英] How to retrieve useful result from subprocess?

查看:99
本文介绍了如何从子有用的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用的语句可以:

b'10.0.3.15'

被转换成

'10.0.3.15'

<一个href=\"http://stackoverflow.com/questions/2592764/what-does-a-b-$p$pfix-before-a-python-string-mean\">What没有一个python字符串前A B preFIX意思?解释了B的意思,但没有回答这个问题。

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.

从外壳可以找到复杂的声明我的IP地址:

From shell can find my IP address with the complex statement :

ip addr show eth0 | awk '$1 == "inet" {gsub(/\/.*$/, "", $2); print $2}'

(来源:<一个href=\"http://stackoverflow.com/questions/23934425/bash-parse-ifconfig-to-get-only-my-ip-address/23934702#23934702\">Bash解析ifconfig来得到的只有我的IP地址)

这对我来说将返回: 10.0.3.15

这是确定的。

现在我想这句话,或任何声明,在Python执行。因为语句有各种特定的令牌,我只写文件,文件读入到变量 CMD

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

我检查 CMD 的内容是相同的上述声明。现在,我在Python执行这个命令:

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]

值为 b'10.0.3.15 \\\\ N'

格式化规范的迷你语言我看到'B'是一个类型,代表二进制文件。

In Format Specification Mini Language I see 'b' is a type which stand for binary.

我只需要 '10 .0.3.15'。如何做到这一点?

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

推荐答案

使用出来,_ = p.communicate()。然后,你的输出保存为变量 A串出。要删除 \\ n 。您可以使用带()(例如 out.strip())。

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())

但是,你应该看一下Python模块 netifaces

import netifaces
device = 'em1'
print(netifaces.ifaddresses(device)[netifaces.AF_INET])

这将输出类似这样:

[{'broadcast': '192.168.23.255', 'netmask': '255.255.255.0', 'addr': '192.168.23.110'}]

这篇关于如何从子有用的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆