1

I'm trying to write a function to parse a traceroute.

It will work if I just have it plain code but not if I put it in a function using a variable. When I put it in a function I get exit code 0 but the list is empty. Works if I replace the variable with a string.

I'm using windows, win11 laptop and a win2016 server. I've tried with different python versions: 3.6, 3.8 & 3.11 Also tried in Idle, pycharm and Visual Code but always the same results.

Most grateful for any help with this, thanks

This works - no function:

import textfsm

# Load the TextFSM template
with open("templates/traceroute_template.textfsm") as template_file:
    template = textfsm.TextFSM(template_file)

# Read the traceroute output from a file or a variable
trace_output = """
1  1.1.1.1  0.735 ms
2  2.2.2.2  0.589 ms
3  3.3.3.3  1.122 ms
"""

# Parse the traceroute output
parsed_data = template.ParseText(trace_output)
print(parsed_data)

Outputs as expected:
[['1', '1.1.1.1'], ['2', '2.2.2.2'], ['3', '3.3.3.3']]

Process finished with exit code 0

However when I try and put it in a function the list comes back empty?

import textfsm

def get_trace():
    # Load the TextFSM template
    with open("templates/traceroute_template.textfsm") as template_file:
        template = textfsm.TextFSM(template_file)

    # Read the traceroute output from a file or a variable
    trace_output = """
    1  1.1.1.1  0.735 ms
    2  2.2.2.2  0.589 ms
    3  3.3.3.3  1.122 ms
    """

    # Parse the traceroute output
    parsed_data = template.ParseText(trace_output)
    print(parsed_data)

get_trace()
Empty list:
[]

Process finished with exit code 0

If within the function I replace the variable with a string including carriage returns it works:

 parsed_data = template.ParseText("""1  1.1.1.1  0.735 ms\r2  2.2.2.2  0.589 ms\r3  3.3.3.3  1.122 ms""")

[['1', '1.1.1.1'], ['2', '2.2.2.2'], ['3', '3.3.3.3']]
Process finished with exit code 0

The template is:

Value Hop (\d+)
Value IP (\S+)

Start
  ^${Hop}\s+${IP} -> Record

2
  • The value of trace_output differs between the two versions of the code. Inside a triple-quoted string, indentation becomes an actual part of the string; the three lines after trace_output = """ need to be flush left. Commented Sep 14, 2023 at 19:33
  • Thank you @jasonharper that has fixed it for me. Not sure if I'm supposed to tick a thank you box here but very much appreciated. Commented Sep 15, 2023 at 14:02

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.