MarkS
MarkS

Reputation: 1539

split() on one character OR another

Python 3.6.0

I have a program that parses output from Cisco switches and routers.

I get to a point in the program where I am returning output from the 'sh ip int brief' command.

I place it in a list so I can split on the '>' character and extract the hostname.

It works perfectly. Pertinent code snippet:

    ssh_channel.send("show ip int brief | exc down" + "\n")
    # ssh_channel.send("show ip int brief" + "\n")
    time.sleep(0.6)
    outp = ssh_channel.recv(5000)
    mystring = outp.decode("utf-8")
    ipbrieflist = mystring.splitlines()
    hostnamelist = ipbrieflist[1].split('>')
    hostname = hostnamelist[0]

If the router is in 'enable' mode the command prompt has a '#' character after the hostname.

If I change my program to split on the '#' character:

    hostnamelist = ipbrieflist[1].split('#')

it still works perfectly.

I need for the program to handle if the output has the '>' character OR the '#' character in 'ipbrieflist'.

I have found several valid references for how to handle this. Ex:

import re
text = 'The quick brown\nfox jumps*over the lazy dog.'
print(re.split('; |, |\*|\n',text))

The above code works perfectly.

However, when I modify my code as follows:

    hostnamelist = ipbrieflist[1].split('> |#')

It does not work. By 'does not work' I mean it does not split on either character. No splitting at all.

The following debug is from PyCharm:

ipbrieflist = mystring.splitlines() ipbrieflist={list}: ['terminal length 0', 'rtr-1841>show ip int brief | exc down', 'Interface'] IP-Address OK? Method Status Protocol', 'FastEthernet0/1 192.168.1.204 YES NVRAM up up ', 'Loopback0 172.17.0.1 YES NVRAM up up ', '', 'rtr-1841>'] hostnamelist = ipbrieflist[1].split('> |#') hostnamelist={list}: ['rtr-1841>show ip int brief | exc down'] hostname = {str}'rtr-1841>show ip int brief | exc down'

As you can see the hostname variable still contains the 'show ip int brief | exc down' appended to it.

I get the same exact behavior if the hostname is followed by the '#' character.

What am I doing wrong?

Thanks.

Upvotes: 1

Views: 880

Answers (1)

John Zwinck
John Zwinck

Reputation: 249153

Instead of this:

ipbrieflist[1].split('> |#')

You want this:

re.split('>|#', ipbrieflist[1])

Upvotes: 1

Related Questions