Python Forum

Full Version: Reading and storing a line of output from pexpect child
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm new to learning pexpect and regex and I'm having some trouble figuring out how to get the output of a command I send and store it in a variable, but for the entire output of that command - I only want to store the rest of 1 specific line after a certain word.

To illustrate - say I have a command that outputs hundreds of lines that all represent certain details of a specific product.

    Color: Maroon Red
    Height: 187cm
    Number Of Seats: 6
    Number Of Wheels: 4
    Material: Aluminum
    Brand: Toyota 
    #and hundreds of more lines...
I want to parse the entire output of the command that I sent which print the details above and only store the material of the product in a variable.

Right now I have something like:

    child.sendline('some command that lists details')
    variable = child.expect(["Material: .*"])
    print(variable)
    child.expect(prompt)
The sendline and expect prompt parts list the details correctly and all, but I'm having trouble figuring out how to parse the output of that command, look for a part that says "Material: " and only store the Aluminum string in a variable.

Right now from playing around I have the variable equal to the value 0 which I guess would be used to verify if a string exists in the output, but I want to access the actual output as a variable and ignore everything after finding a certain string and only include what's after that string on the line for which the the string is located on.

So instead of having variable equal to and print a value of 0, it should instead print the word "Aluminum".

Is there a way to do this using regex? I'm trying to get used to using regex expressions so I would prefer a solution using that but if not, I'd still appreciate any help!

I'm also editing my code in vim and using linux if that helps.

Update:

I found something online like:

[\n\r].*Object Name:\s*([^\n\r]*)
which would get the stuff after Object Name: but I wasn't sure how I would store this in my code. Would I do something like:

variable = exp.expect([\n\r].*Object Name:\s*([^\n\r]*)) 
child.sendline('some command that lists details')
child.expect(prompt)
output = child.before.decode()
what_you_want = [i.split(':')[1].strip() for i in output.split('\n') if 'Material' in i][0]



#above code should suffice.
I know it is too late, but hope it can still be useful for you elsewhere. Wink