How to extract particlar message from a vast displayed output using python regular expression?

2024/7/8 8:27:40
  1. Firstly in the code, i would like to know How can i add a for loop for CH (1-11) instead of writing for every number
  2. Also how to extract SUCCESS and FAILED message from the output (reference) For example i want the output as

CH1 : Failed

CH2: SUCCESS

CH3: Failed

: so on

I want to use regular expression and not json for this.

import pexpectdef quick_test():   ch = pexpect.spawn('ssh to server')ch.logfile = sys.stdoutch.expect("Select channels")print ("\n########################################\n")ch.sendline("1")ch.expect("Enter ch to run:")ch.sendline("CH1,0")var1=ch.afterprint(var1)ch.expect("Enter Test:")var2=ch.beforeprint(var2)ch.sendline("CH2,0")ch.expect("Enter Test:")var3=ch.beforeprint(var3)ch.sendline("CH3,0")ch.expect("Enter Test:")var4=ch.beforeprint(var4)ch.sendline("CH4,0")ch.expect("Enter Test:")var5=ch.beforeprint(var5)ch.sendline("CH5,0")ch.expect("Enter Test:")var6=ch.beforeprint(var6)ch.sendline("CH6,0")ch.expect("Enter Test:")var7=ch.beforeprint(var7)ch.sendline("CH7,0")ch.expect("Enter Test:")var8=ch.beforeprint(var8)ch.sendline("CH8,0")ch.expect("Enter Test:")var9=ch.beforeprint(var9)ch.sendline("CH9,0")ch.expect("Enter Test:")var10=ch.beforeprint(var10)ch.sendline("CH10,0")ch.expect("Enter Test:")var11=ch.beforeprint(var11)ch.sendline("CH11,0")if __name__ == '__main__':quick_test()

output:

    output###########################################There are plenty of output displayed in which these below lines are included and not in the given order and are displayed randomly.CH1,0 Result: FAILED
CH2,0 Result: SUCCESS
CH3,0 Result: FAILED
CH4,0 Result: SUCCESS
CH5,0 Result: SUCCESS
CH6,0 Result: SUCCESS
CH7,0 Result: FAILED
CH8,0 Result: SUCCESS
CH9,0 Result: FAILED
CH10,0 Result: SUCCESS
CH11,0 Result: FAILED
Answer

1. Firstly in the code, i would like to know How can i add a for loop for CH (1-11) instead of writing for every number

Your basic repeatable unit, starting on "CH2", is:

ch.sendline("CH2,0")
ch.expect("Enter Test:")
var3=ch.before
print(var3)

Instead of using named variables, we will use a single variable holding a list data structure to hold n values:

vars = []

We use a for loop to iterate up to 11:

for i in range(11):ch.sendline("CH{},0".format(i+1))ch.expect("Enter Test:")vars[i]=ch.beforeprint(vars[i])

The first variable is handled differently, so we deal with it outside the loop:

vars = []
ch.expect("Enter ch to run:")
ch.sendline("CH1,0")
var1s[0]=ch.after
print(var1)
for i in range(1, 11):ch.sendline("CH{},0".format(i+1))ch.expect("Enter Test:")vars[i]=ch.beforeprint(vars[i])

This should print the same text to the display, and your values should still be stored in the vars list. For example, what used to be in var8 will now be in vars[7] (since arrays are zero-indexed).

2. Also how to extract SUCCESS and FAILED message from the output (reference)

Use a RegEx, such as this pattern:

^(CH\d{1,}),0 Result: (SUCCESS|FAILED)$

You will get the desired strings in two positional capture groups.

You can match against each line in the output (assuming this output is stored somewhere, such as read in from a file, and not simply printed to the display) by again using a for loop.

Make use of Python's re module:

pattern = r"^(CH\d{1,}),0 Result: (SUCCESS|FAILED)$" # r-string
sampleOutputLine = "CH1,0 Result: FAILED"
m = re.match(pattern, sampleOutputLine)print(m.groups())

Output:

('CH1', 'FAILED')

You can then format the groups as desired, for example as:

formattedOutputLine = "{}: ".format(m.groups[0])
if m.groups[1] === "SUCCESS":formattedOutputLine += m.groups[1]
else:formattedOutputLine += m.groups[1].lower()

Assuming the output lines are stored as a list of strings in the variable output, where each string is a line:

pattern = r"^(CH\d{1,}),0 Result: (SUCCESS|FAILED)$" # r-stringformattedOutput = []
for line in output:m = re.match(pattern, line) # consider compiling the pattern beforehand if your output is large, for performanceformattedOutputLine = "{}: ".format(m.groups[0])
if m.groups[1] === "SUCCESS":formattedOutputLine += m.groups[1]
else:formattedOutputLine += m.groups[1].lower()formattedOutput.append(formattedOutputLine)
https://en.xdnf.cn/q/119452.html

Related Q&A

Enemy health bar aint draining pygame [duplicate]

This question already has answers here:How to put a health bar over the sprite in pygame(2 answers)Closed 3 years ago.Okay so I was trying to make a health bar for my enemy class and only a part of it …

Python - Create and instantiate class

I am building a class of playlists, which will hold many playlists of the same genre.class playlist(object):def __init__(self,name):self.name = nameI would like to instantiate them passing the user:def…

Missing samples of a dataframe in pandas

My df:In [163]: df.head() Out[163]: x-axis y-axis z-axis time 2017-07-27 06:23:08 -0.107666 -0.068848 0.963623 2017-07-27 06:23:08 -0.105225 -0.070068 0.963867 .....I set the index as dateti…

How to hide a button after clicked in Python

I was wondering how to hide my start button after being clicked so that If the user accidentally was clicker happy they wouldnt hit the button causing more bubbles to appear on screen. Below is a snipp…

Unable to click on QRadioButton after linking it with QtCore.QEventLoop()

Few days back i had situation where i had to check/uncheck QRadioButton in for loop. Here is the link Waiting in for loop until QRadioButton get checked everytime? After implementing QEventLoop on thi…

Distance Matrix Haversine

I am working on a data frame that looks like this :lat lon id_zone 0 40.0795 4.338600 1 45.9990 4.829600 2 45.2729 2.882000 3 45.7336 4.850478 4 45.6981 5.…

python google geolocation api using wifi mac

Im trying to use Googles API for geolocation giving wifi data to determine location. This is their intro. And this is my code@author: Keith """import requestspayload = {"c…

Python requests and variable payload

Reticulated members,I am attempting to use a GET method that is supported against the endpoint. However, I am using python and wanting to pass the user raw_input that is assigned to a variable:uid = ra…

How should I read and write a configuration file for TkInter?

Ive gathered numbers in a configuration file, and I would like to apply them to buttons. Clicking the button should allow the number to be changed and then re-written to the config file. My current cod…

How to convert this nested dictionary into one single dictionary in Python 3? [duplicate]

This question already has answers here:Convert nested dictionary into a dictionary(2 answers)Flatten nested dictionaries, compressing keys(32 answers)Closed 4 years ago.I have a dictionary like this:a …