[英]subprocess with pipes python
我想執行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
我寫了一個例子來理解:
碼:
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())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.