[英]os.system giving weird output in linux
我在 suse linux 中運行這個 python 函數來從 /etc/hosts 中 grep 節點的 ip--
def mm_node():
import os
node_name = os.system("`cat /etc/hosts | egrep -i mm | grep om | awk '{print $1}'`")
return node_name
mm_node()
結果,它顯示了這個奇怪的輸出
sh: 192.168.10.10: command not found
代替
192.168.10.10
如果我運行 shell 命令
( cat /etc/hosts | egrep -i mm | grep om | awk '{print $1}'
)
直接在 linux 命令提示符下,它給出了 o/p 作為
192.168.10.10
反引號告訴 shell 捕獲輸出並在命令行上使用它,通常作為命令的參數,如grep `whoami` /etc/passwd
。 在您的情況下,命令行僅包含一個反引號管道,因此 shell 將管道的輸出解釋為要執行的命令。 這就是為什么它抱怨 IP 地址“未找到”的原因。
如果你的目的是捕捉到管道的輸出Python代碼的使用,你應該使用的subprocess
模塊,這是現代的替代os.system
,可以使輸出的容易捕捉。 例如:
import subprocess
def mm_node():
output = subprocess.run(
"cat /etc/hosts | egrep -i mm | grep om | awk '{print $1}'",
shell=True,
capture_output=True
).stdout
return output.strip()
print(mm_node())
def mm_node():
import os
node_name = os.system("cat /etc/hosts | egrep -i mm | grep om | awk '{print $1}'")
return node_name
mm_node()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.