Home > front end >  extract specific element from string in python
extract specific element from string in python

Time:06-07

I have to extract data after executing commands on shell. I am able to execute command and capture output in the form of string. Below is the sample string output from which I have to extract each field of "uptime" command output e.g Last restart occurred at, Time since restart etc. I tried to convert it in dictionary but applied method is not working. Please provide your inputs if possible.

Sample String:

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

CodePudding user response:

The output you receive is of type bytes. Call its decode() method to transform it to a str.

Iterate through each line of the string and set a flag (uptime_output_reached) once the uptime output has started. Once that flag has been set, the following lines will be split into 2 strings at the first occurrence of : . These will be the key, value pairs used to store the uptime results.

What did you attempt? Edit your question with the code you tried, even if it didn't work.

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

Output:

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'

CodePudding user response:

as an alternative as @GordonAitchJay described, you can use regexp something like this:

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

import re

match = re.search( r'---->(. ?)---->', sample.decode(), re.S )
uptime = match[1] if match else ''

print( uptime )
  • Related