在python中从字符串中提取特定元素



我必须在shell上执行命令后提取数据。我能够以字符串的形式执行命令和捕获输出。下面是示例字符串输出,我必须从中提取"uptime"命令输出,如上次重启发生在,重启后的时间等。我试图在字典中转换它,但应用的方法不起作用。

示例字符串:

b'rnrn adjDisc/, adjprov/, ains/, alarm/, alatypes/, almBase/, ALPL/, alrmst, ALSO/, rn applblki/, aTrace/, BackPlane/, baseUtils/, brownout/, bwm/, cac/, cdb/, rn chkpt/, CLAF/, clustering/, cmnfpga/, comms/, config/, configFile/, control/, rn cpl, cplutils/, create_file, csclient/, dasm_cfm/, datasync/, dbalrms/, rn dbman/, dbrst/, ddf/, decommission/, diplasons/, doc/, dov/, ds1tm/, rn dsbl/, edf, ehf/, epl/, EqptAttr/, eqptgrp/, eqpt_mode/, eqpt_stats/,rn eslots/、fhgraph/、filesync/、flashBurn/、flightrec/、fpo/、fsm/、ftp/、rn ftpClient/、gzip/、hal/、hdsmlinkdata/、heapStats/、httpc/、i2c/、imon/、ins/、rn intDiag/、intrrpts/、ipc/、ipm/、irq1/、irq2/、IRQ6/、isc/、l2Services/、rn leds/、loadinfo/、loadMgmt/、logs/、lua/、manufacturing/、memStats、rn misconnection/、mmon/、mofshadow/、nbi_common_utils/、necht/、niapp/、nlc/、rn nncli/、oamfac/、obm/、observer/、opmCtrl/、opmCtrlFlex/、OSRP/、otdr/、rn owireci/、passive_slots/, pathopt/, pbe/, pdns/, PhotonicNBI/, rn photonicsNVSRecovery/, photonic_ots/, photop/, plog/, PM/, PM/, pmbase/, rn pmp/, pods/, powerAudit/, pramUtil/, ras/, RASDBGI, rdbg, rmcemon/, rn round_trip_delay/, rpr/, rtrvlog/, sbf/, scmpml/, secure_erase_cmn/, rn setpriv, shelfinfo/, shelfSync/, slc/, slotseq/, snmp/, SNMPTranslator/, rn socKernel/, socLa/, SONMP/, sorn/, sov/, spfpga/, spsid_dump, rn SpSwSubFailReason, spsync/, sptools/, svrest/, sync/, tar/,targetshell/, rn tcsdebug/, tdrf/, tdrfShow, teas/, telnet/, tidci/, tl1ci/, TL1EvtSeq/, TL1EvtSeq/, tod/, top/, tpUtl/, tr/, trace/, tracepoints/, TRCntrl/, rn ts1forn/, tsam/, tsbase/, tsds3ec1/, tsemotr/, tsexer/, tsfpo/, tsl2/, rn tsmdd_qry/, tsm_prov/, tsm_sbf/, tsngm/, tsotnsw/, tsplug/, tsprot/, rn tsprsta/, tssmux/, tsstm1ee4/, tsxc_sbf/, ts_allocation/, ud2_fwd/, udp_fwd/, rn upgrade/, uptime, vbus/, vfs/, vfs_signal_debug/, vkgcct/, vkgfan/, vkginv/rn vkgio/, vkgpwr/, vk_i2c_acc/, vneProxy/, vosa/, *=quitrnrnTID="Sub_6500_3":Shelf=1rnSlot15-docInst: unset, ome_sp2_vx_appl: OME1280。BPrnCommand完成于2022年6月7日星期二- 04:58:42 (UTC)rnrn---->~ uptime r n最后一次重启发生在:FRI MAY 27, 2022 at 07:42:31 (UTC)r n自重启以来的时间:10天21小时16分13秒rnrnActual累计正常运行时间:489天7小时30分钟rnLogged累计正常运行时间:488天11小时54分钟rnrnActual连续正常运行时间:118天15小时47分钟rnrnCommand完成于TUE JUN 07, 2022 - 04:58:44 (UTC)rnrn---->'

您收到的输出类型为bytes。调用其decode()方法将其转换为str

遍历字符串的每一行,并在uptime输出开始后设置一个标志(uptime_output_reached)。一旦设置了该标志,以下行将在第一次出现:时被分成2个字符串。这些将是用于存储正常运行时间结果的键、值对。

你尝试了什么?用你试过的代码编辑你的问题,即使它不起作用。

output_bytes = b'rnrn  adjDisc/, adjprov/, ains/, alarm/, alatypes/, almBase/, ALPL/, alrmst, ALSO/, rn  applblki/, aTrace/, BackPlane/, baseUtils/, brownout/, bwm/, cac/, cdb/, rn  chkpt/, CLAF/, clustering/, cmnfpga/, comms/, config/, configFile/, control/, rn  cpl, cplutils/, create_file, csclient/, dasm_cfm/, datasync/, dbalrms/, rn  dbman/, dbrst/, ddf/, decommission/, diag/, difReasons, doc/, dov/, ds1tm/, rn  dsbl/, edf, ehf/, epl/, EqptAttr/, eqptgrp/, eqpt_mode/, eqpt_stats/, rn  eslots/, fhgraph/, filesync/, flashBurn/, flightrec/, fpo/, fsm/, ftp/, rn  ftpClient/, gzip/, hal/, hdsmlinkdata/, heapStats, httpc/, i2c/, imon/, ins/, rn  intDiag/, intrrpts/, ipc/, ipm/, irq1/, irq2/, IRQ6/, isc/, l2Services/, rn  leds/, loadinfo/, loadMgmt/, logs/, lua/, manufacturing/, memStats, rn  misconnection/, mmon/, mofshadow/, nbi_common_utils/, necht/, niapp/, nlc/, rn  nncli/, oamfac/, obm/, observer/, opmCtrl/, opmCtrlFlex/, OSRP/, otdr/, rn  owireci/, passive_slots/, pathopt/, pbe/, pdns/, PhotonicNBI/, rn  photonicsNVSRecovery/, photonic_ots/, photop/, plog/, PM/, pm/, pmbase/, rn  pmp/, pods/, powerAudit/, pramUtil/, ras/, RASDBGI, rdbg, rmcemon/, rn  round_trip_delay/, rpr/, rtrvlog/, sbf/, scmpml/, secure_erase_cmn/, rn  setpriv, shelfinfo/, shelfSync/, slc/, slotseq/, snmp/, SNMPTranslator/, rn  socKernel/, socLa/, SONMP/, sorn/, sov/, spfpga/, spsid_dump, rn  SpSwSubFailReason, spsync/, sptools/, svrest/, sync/, tar/, targetshell/, rn  tcsdebug/, tdrf/, tdrfShow, teas/, telnet/, tidci/, tl1ci/, TL1EvtSeq/, rn  tl1_to_avp/, tod/, top/, tpUtl/, tr/, trace/, tracepoints/, TRCntrl/, rn  ts1forn/, tsam/, tsbase/, tsds3ec1/, tsemotr/, tsexer/, tsfpo/, tsl2/, rn  tsmdd_qry/, tsm_prov/, tsm_sbf/, tsngm/, tsocn/, tsotnsw/, tsplug/, tsprot/, rn  tsprsta/, tssmux/, tsstm1ee4/, tsxc_sbf/, ts_allocation/, ud2_fwd/, udp_fwd/, rn  upgrade/, uptime, vbus/, vfs/, vfs_signal_debug/, vkgcct/, vkgfan/, vkginv/, rn  vkgio/, vkgpwr/, vk_i2c_acc/, vneProxy/, vosa/, *=quitrnrnTID="Sub_6500_3":Shelf=1rnSlot15-docInst: unset, ome_sp2_vx_appl: OME1280.BPrnCommand completed at TUE JUN 07, 2022 - 04:58:42 (UTC)rnrn----> ~ uptime rnLast restart occurred at: FRI MAY 27, 2022 at 07:42:31 (UTC) rnTime since restart: 10 days 21 hrs 16 mins 13 secsrnrnActual Cumulative uptime: 489 days 7 hrs 30 minsrnLogged Cumulative uptime: 488 days 11 hrs 54 minsrnrnActual Continuous uptime: 118 days 15 hrs 47 minsrnrnCommand completed at TUE JUN 07, 2022 - 04:58:44 (UTC)rnrn----> '
output = output_bytes.decode()
uptime_output_reached = False
uptime_results = {}
for line in output.splitlines():
if line == "----> ~ uptime ":
uptime_output_reached = True
continue

if uptime_output_reached:
if ": " in line:
key, value = line.split(": ", 1)
uptime_results[key] = value
print("uptime results:")
for key, value in uptime_results.items():
print(f"'{key}': '{value}'")

输出:

uptime results:
'Last restart occurred at': 'FRI MAY 27, 2022 at 07:42:31 (UTC) '
'Time since restart': '10 days 21 hrs 16 mins 13 secs'
'Actual Cumulative uptime': '489 days 7 hrs 30 mins'
'Logged Cumulative uptime': '488 days 11 hrs 54 mins'
'Actual Continuous uptime': '118 days 15 hrs 47 mins'

作为@GordonAitchJay描述的替代方案,您可以像这样使用regexp:

sample = b'rnrn  adjDisc/, adjprov/, ains/, alarm/, alatypes/, almBase/, ALPL/, alrmst, ALSO/, rn  applblki/, aTrace/, BackPlane/, baseUtils/, brownout/, bwm/, cac/, cdb/, rn  chkpt/, CLAF/, clustering/, cmnfpga/, comms/, config/, configFile/, control/, rn  cpl, cplutils/, create_file, csclient/, dasm_cfm/, datasync/, dbalrms/, rn  dbman/, dbrst/, ddf/, decommission/, diag/, difReasons, doc/, dov/, ds1tm/, rn  dsbl/, edf, ehf/, epl/, EqptAttr/, eqptgrp/, eqpt_mode/, eqpt_stats/, rn  eslots/, fhgraph/, filesync/, flashBurn/, flightrec/, fpo/, fsm/, ftp/, rn  ftpClient/, gzip/, hal/, hdsmlinkdata/, heapStats, httpc/, i2c/, imon/, ins/, rn  intDiag/, intrrpts/, ipc/, ipm/, irq1/, irq2/, IRQ6/, isc/, l2Services/, rn  leds/, loadinfo/, loadMgmt/, logs/, lua/, manufacturing/, memStats, rn  misconnection/, mmon/, mofshadow/, nbi_common_utils/, necht/, niapp/, nlc/, rn  nncli/, oamfac/, obm/, observer/, opmCtrl/, opmCtrlFlex/, OSRP/, otdr/, rn  owireci/, passive_slots/, pathopt/, pbe/, pdns/, PhotonicNBI/, rn  photonicsNVSRecovery/, photonic_ots/, photop/, plog/, PM/, pm/, pmbase/, rn  pmp/, pods/, powerAudit/, pramUtil/, ras/, RASDBGI, rdbg, rmcemon/, rn  round_trip_delay/, rpr/, rtrvlog/, sbf/, scmpml/, secure_erase_cmn/, rn  setpriv, shelfinfo/, shelfSync/, slc/, slotseq/, snmp/, SNMPTranslator/, rn  socKernel/, socLa/, SONMP/, sorn/, sov/, spfpga/, spsid_dump, rn  SpSwSubFailReason, spsync/, sptools/, svrest/, sync/, tar/, targetshell/, rn  tcsdebug/, tdrf/, tdrfShow, teas/, telnet/, tidci/, tl1ci/, TL1EvtSeq/, rn  tl1_to_avp/, tod/, top/, tpUtl/, tr/, trace/, tracepoints/, TRCntrl/, rn  ts1forn/, tsam/, tsbase/, tsds3ec1/, tsemotr/, tsexer/, tsfpo/, tsl2/, rn  tsmdd_qry/, tsm_prov/, tsm_sbf/, tsngm/, tsocn/, tsotnsw/, tsplug/, tsprot/, rn  tsprsta/, tssmux/, tsstm1ee4/, tsxc_sbf/, ts_allocation/, ud2_fwd/, udp_fwd/, rn  upgrade/, uptime, vbus/, vfs/, vfs_signal_debug/, vkgcct/, vkgfan/, vkginv/, rn  vkgio/, vkgpwr/, vk_i2c_acc/, vneProxy/, vosa/, *=quitrnrnTID="Sub_6500_3":Shelf=1rnSlot15-docInst: unset, ome_sp2_vx_appl: OME1280.BPrnCommand completed at TUE JUN 07, 2022 - 04:58:42 (UTC)rnrn----> ~ uptime rnLast restart occurred at: FRI MAY 27, 2022 at 07:42:31 (UTC) rnTime since restart: 10 days 21 hrs 16 mins 13 secsrnrnActual Cumulative uptime: 489 days 7 hrs 30 minsrnLogged Cumulative uptime: 488 days 11 hrs 54 minsrnrnActual Continuous uptime: 118 days 15 hrs 47 minsrnrnCommand completed at TUE JUN 07, 2022 - 04:58:44 (UTC)rnrn----> '
import re
match = re.search( r'---->(.+?)---->', sample.decode(), re.S )
uptime = match[1] if match else ''
print( uptime )

相关内容

  • 没有找到相关文章

最新更新