Search code examples
python-3.xerror-handlingstdoutqualys

How to get error message content from console?


I have the following text as log output (to the python console), when running a script agains the Qualys API and would like to parse the content of in the error message ("Error! Received A 4xx...)from there. I am using the qualysapi modul. Based on what I see in the module it creates an own logger instance and unfortunatelly the printed message is not contained in the raised exception by the module.

Any hints how such a thing would be possible?

      i     | Loading new data into Qualys...

Error! Received a 4XX client error or 5XX server error response.

Content = 
<!DOCTYPE SIMPLE_RETURN SYSTEM "<....>">
<SIMPLE_RETURN>
  <RESPONSE>
    <DATETIME>2021-11-20T17:07:40Z</DATETIME>
    <CODE>1905</CODE>
    <TEXT>parameter IPs has invalid value: One or more IPs are not assigned to this user: 10.73.32.133, 10.73.32.139-10.73.32.171, </TEXT>
  </RESPONSE>
</SIMPLE_RETURN>

      i     | Adding missing IPs to subscription, then we try again...

Solution

  • You can redirect stdout or stderr to a file and then process the file:

    import sys
    sys.stdout = open('file', 'w')
    print('test')
    sys.stdout.close()
    

    Check more about this here: Redirect stdout to a file in Python?