管道python的子流程

时间:2019-07-23 10:57:43

标签: python bash subprocess pipe

我想执行bash命令以获取我的默认界面:

ip route list | grep default | awk '{print $5}'

我想要这个,但是在python脚本中,所以我尝试了:

    cmd = "ip route list | grep default | awk '{print $5}'"
    ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    output = ps.communicate()[0]
    print(output)

但是它给了我b'wlan0\n'而不是wlan0的答案...我还有什么其他解决方案,或者我在哪里出错了?

1 个答案:

答案 0 :(得分:0)

获取b'wlan0\n'值的类型为bytes,因此您需要对其进行解码。通常使用utf-8

str/bytes类型的处理与Python2Python3之间有很大的区别。这些网站包含有关它的更多详细信息:

我写了一个例子来理解:

代码:

bytes_var = b"wlan0"
string_var = "wlan0"
print("Type: {type}, Value: {val}".format(type=type(bytes_var),
                                          val=bytes_var))
print("Type: {type}, Value: {val}".format(type=type(string_var),
                                          val=string_var))
print("Type: {type}, Value: {val}".format(type=type(bytes_var.decode("utf-8")),
                                          val=bytes_var.decode("utf-8")))

输出:

>>> python3 test.py 
Type: <class 'bytes'>, Value: b'wlan0'
Type: <class 'str'>, Value: wlan0
Type: <class 'str'>, Value: wlan0

此外,您当然可以使用x.strip()删除尾随空白。

因此,在您的情况下,您应该使用以下行:

print(output.decode("utf-8")).strip())