【问题标题】:subprocess with pipes python带有管道python的子进程
【发布时间】:2019-12-01 09:46:16
【问题描述】:

我想执行一个 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的答案...我还有哪些其他解决方案或我在哪里犯了错误?

【问题讨论】:

  • 使用output.decode("utf-8")
  • ……也许还有.strip()
  • 这是正确的。
  • 非常感谢解码和剥离的组合是完美的

标签: python bash subprocess pipe


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-03-21
    • 2017-03-10
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多