[英]Store filtered output of cmd command in a variable
我試圖將cmd命令的輸出存儲為python中的變量。 為了實現這一點,我使用的是os.system()
但os.system()
只是運行進程,它不捕獲輸出。
import os
PlatformName = os.system("adb shell getprop | grep -e 'bt.name'")
DeviceName = os.system("adb shell getprop | grep -e '.product.brand'")
DeviceID = os.system("adb shell getprop | grep -e 'serialno'")
Version = os.system("adb shell getprop | grep -e 'version.release'")
print(PlatformName)
print(DeviceName)
print(DeviceID)
print(Version)
然后我嘗試使用subprocess
模塊。
import subprocess
import os
PlatformName = subprocess.check_output(["adb shell getprop | grep -e 'bt.name'"])
DeviceName = subprocess.check_output(["adb shell getprop | grep -e '.product.brand'"])
DeviceID = subprocess.check_output(["adb shell getprop | grep -e 'serialno'"])
Version = subprocess.check_output(["adb shell getprop | grep -e 'version.release'"])
print(PlatformName)
print(DeviceName)
print(DeviceID)
print(Version)
我收到以下錯誤
FileNotFoundError:[WinError 2]系統找不到指定的文件
如何將命令的輸出存儲為變量?
這里的問題:
shell=True
因為它有一點工作機會,並且shell=True
以安全問題而聞名(以及其他問題,如非可移植性) grep
在windows上不是標准的,而且模式是正則表達式,這意味着你可能不得不逃避.
( "bt\\.name"
)。 grep
返回1並且會使check_output
失敗。 grep
返回匹配項和換行符時,你必須刪除它 我改寫了這個:
PlatformName = subprocess.check_output(["adb shell getprop | grep -e 'bt.name'"])
如:
output = subprocess.check_output(["adb","shell","getprop"])
platform_name = next((line for line in output.decode().splitlines() if "bt.name" in line),"")
第二行是grep的“本機”版本(沒有正則表達式)。 它返回輸出行中第一次出現的“bt.line”,如果沒有找到則返回空字符串。
你在這里不需要grep
(上面不是嚴格等同的,因為它產生了第一次出現,而不是所有的出現,但在你的情況下應該沒問題)。 並且您的客戶可能沒有在Windows上安裝grep
。
嘿,我遇到了和你一樣的問題。 即使shell=False
子流程也可以做你想要的。 技巧是communic()方法。
with subprocess.Popen(cmdCode,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd = workingDir,
bufsize=1,
universal_newlines = True) as proc:
#output is stored in proc.stdout
#errors are stored in proc.stderr
現在你需要一個小函數來掃描proc.stdout
以獲取所需的信息: PlatformName
等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.