从linux命令输出的python返回列表

时间:2014-11-12 19:08:50

标签: python linux list tuples popen

我是python的新手,我正在快速学习,但这超出了我目前的理解水平。我试图将linux命令apcaccess的输出拉入python中的列表。

apcaccess是一个获取APC UPS状态的linux命令。输出是这样的:

$ apcaccess
APC      : 001,035,0933
DATE     : 2014-11-12 13:38:27 -0500  
HOSTNAME : doormon
VERSION  : 3.14.10 (13 September 2011) debian
UPSNAME  : UPS
CABLE    : USB Cable
DRIVER   : USB UPS Driver
UPSMODE  : Stand Alone
STARTTIME: 2014-11-12 12:28:00 -0500  
MODEL    : Back-UPS ES 550G 
STATUS   : ONLINE 
LINEV    : 118.0 Volts
LOADPCT  :  15.0 Percent Load Capacity
BCHARGE  : 100.0 Percent
TIMELEFT :  46.0 Minutes
MBATTCHG : 5 Percent
MINTIMEL : 3 Minutes
MAXTIME  : 0 Seconds
SENSE    : Medium
LOTRANS  : 092.0 Volts
HITRANS  : 139.0 Volts
ALARMDEL : 30 seconds
BATTV    : 13.6 Volts
LASTXFER : No transfers since turnon
NUMXFERS : 2
XONBATT  : 2014-11-12 12:33:35 -0500  
TONBATT  : 0 seconds
CUMONBATT: 53 seconds
XOFFBATT : 2014-11-12 12:33:43 -0500  
STATFLAG : 0x07000008 Status Flag
SERIALNO : 4B1335P17084  
BATTDATE : 2013-08-28
NOMINV   : 120 Volts
NOMBATTV :  12.0 Volts
FIRMWARE : 904.W1 .D USB FW:W1
END APC  : 2014-11-12 13:38:53 -0500

我尝试了Popen的不同迭代,例如:

def check_apc_ups():
  output = subprocess.Popen("apcaccess", stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
  x1, x2, x3, x4, x5 = output

我希望能够将每一行拉入包含全部32的列表或元组,然后仅显示/打印我需要的内容,例如TIMELEFTBCHARGE

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

from subprocess import check_output
out = check_output(["apcaccess"])

spl = [ele.split(":",1)for ele in out.splitlines()]
d = {k.rstrip():v.lstrip() for k,v in spl}

print(d['BCHARGE'])
print(d["TIMELEFT"])
100.0 Percent
46.0 Minutes


from subprocess import check_output
def get_apa():
    out = check_output(["apcaccess"])
    spl = [ele.split(":", 1) for ele in out.splitlines()]
    d = {k.rstrip(): v.lstrip() for k, v in spl}
    return d

output = get_apa()
print (output['BCHARGE'])
100.0 Percent

打印所有键/值配对:

for k,v in get_apa().items():
    print("{} = {}".format(k,v))

答案 1 :(得分:1)

已经有答案如何将命令输出到python中。

目前尚不清楚您将如何处理输出。也许,字典(字典)比列表更好:

# stolen from Hackaholic's answer
import subprocess
child = subprocess.Popen('apcaccess',stdout=subprocess.PIPE)
msg,err = child.communicate()

# now create the dict:
myDict={}
#for i in msg.split("\n"):  # loop over lines
for i in msg.splitlines():  # EDIT: See comments  
    splitted=i.split(":")  # list like ["HOSTNAME ", " doormon"]
    # remove leading & trailing spaces, add to dict
    myDict[splitted[0].strip()]=splitted[1].strip() 


#Now, you can easily access the items:
print myDict["SERIALNO"]
print myDict["STATUS"]
print myDict["BATTV"]

for k in myDict.keys():
    print k +" = "+ myDict[k]

答案 2 :(得分:0)

您需要的是subprocess模块

import subprocess
child = subprocess.Popen('apcaccess',stdout=subprocess.PIPE)
msg,err = child.communicate()
print(msg.split())