我要执行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
…我还有什么其他的解决方案,或者我在哪里犯了错误?你知道吗
获取
b'wlan0\n'
值的类型是bytes
,因此需要对其进行解码。通常使用utf-8
。你知道吗str/bytes
类型处理是Python2
和Python3
之间的一大区别。这些网站包含有关它的更多详细信息:http://python3porting.com/problems.html#bytes-strings-and-unicode
https://timothybramlett.com/Strings_Bytes_and_Unicode_in_Python_2_and_3.html
我写了一个小例子来理解:
代码:
输出:
此外,当然可以使用
x.strip()
删除后面的空格。你知道吗因此,在您的情况下,您应该使用以下行:
相关问题 更多 >
编程相关推荐