1

I have an API which gets the success or error message on console.I am new to python and trying to read the response. Google throws so many examples to use subprocess but I dont want to run,call any command or sub process. I just want to read the output after below API call.

This is the response in console when success

17:50:52 | Logged in!!

This is the github link for the sdk and documentation

https://github.com/5paisa/py5paisa

This is the code

from py5paisa import FivePaisaClient

email = "myemailid@gmail.com"
pw = "mypassword"
dob = "mydateofbirth"
cred={
    "APP_NAME":"app-name",
    "APP_SOURCE":"app-src",
    "USER_ID":"user-id",
    "PASSWORD":"pw",
    "USER_KEY":"user-key",
    "ENCRYPTION_KEY":"enc-key"
    }

client = FivePaisaClient(email=email, passwd=pw, dob=dob,cred=cred)
client.login()
Mohan
  • 13
  • 3
  • 1
    Does this answer your question? [How to capture stdout output from a Python function call?](https://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call) – Alex Sveshnikov Jun 10 '22 at 12:21
  • 1
    Please Mohan, if one of our response answered your question, can you validate it. If you found another better solution, you can answer your own question to help others. – vinalti Jul 12 '22 at 08:17

2 Answers2

0

In general it is bad practice to get a value from STDOUT. There are some ways but it's pretty tricky (it's not made for it). And the problem doesn't come from you but from the API which is wrongly designed, it should return a value e.g. True or False (at least) to tell you if you logged in, and they don't do it.

So, according to their documentation it is not possible to know if you're logged in, but you may be able to see if you're logged in by checking the attribute client_code in the client object.

If client.client_code is equal to something then it should be logged in and if it is equal to something else then not. You can try comparing it's value when you successfully login or when it fails (wrong credential for instance). Then you can put a condition : if it is None or False or 0 (you will have to see this by yourself) then it is failed.

Can you try doing the following with a successful and failed login:

client.login()
print(client.client_code)

Source of the API:

# Login function :
           # (...)
            message = res["body"]["Message"]
            if message == "":
                log_response("Logged in!!")
            else:
                log_response(message)
            self._set_client_code(res["body"]["ClientCode"])
           # (...)

# _set_client_code function :
    def _set_client_code(self, client_code):
        try:
            self.client_code = client_code   # <<<< That's what we want
        except Exception as e:
            log_response(e)
vinalti
  • 966
  • 5
  • 26
0

Since this questions asks how to capture "stdout" one way you can accomplish this is to intercept the log message before it hits stdout. The minimum code to capture a log message within a Python script looks this:

#!/usr/bin/env python3

import logging

logger = logging.getLogger(__name__)


class RequestHandler(logging.Handler):
  def emit(self, record):
    if record.getMessage().startswith("Hello"):
      print("hello detected")

handler = RequestHandler()
logger.addHandler(handler)
logger.warning("Hello world")

Putting it all together you may be able to do something like this:

import logging

from py5paisa import FivePaisaClient

email = "myemailid@gmail.com"
pw = "mypassword"
dob = "mydateofbirth"
cred={
    "APP_NAME":"app-name",
    "APP_SOURCE":"app-src",
    "USER_ID":"user-id",
    "PASSWORD":"pw",
    "USER_KEY":"user-key",
    "ENCRYPTION_KEY":"enc-key"
    }

client = FivePaisaClient(email=email, passwd=pw, dob=dob,cred=cred)


class PaisaClient(logging.Handler):

  def __init__():
    self.loggedin = False  # this is the variable we can use to see if we are "logged in"

  def emit(self, record):
    if record.getMessage().startswith("Logged in!!")
      self.loggedin = True

  def login():
    client.login()

logging.getLogger(py5paisa) # get the logger for the py5paisa library
# tutorial here: https://betterstack.com/community/questions/how-to-disable-logging-from-python-request-library/
logging.basicConfig(handlers=[PaisaClient()], level=0, force=True)

c = PaisaClient()
c.login()
daodennis
  • 23
  • 4