Redirecting Print() from the backend to a Dash application

Hi all,

I am developing a Dash application to interface with a Python package. The structure of the application can be summarised as follows:

  1. A normal Python package with module and sub-packages;
  2. A Dash application to control the Python package.

The structure is as follows:

  • package
    • main scripts
    • usermessage.py
    • sub-package 1 (with other scripts)
    • gui
      • dashapp.py
      • other GUI parts
      • callback scripts

I want to separate the two elements. This structure allows me to develop the frontend and backend efficiently. In addition, the package has to be launched via the command line interface and the Dash application.

My Python script contains a command to print user messages: i.e. in the usermessage.py script:

def printusermessage(msg,verbose=True,log=None): 
       if verbose == True: 
              print(msg)
       if not log == None: 
              # Save the msg in a log file. 

But my aim is to redirect the message printed by this function to a Dash TextArea component. I have not idea how I can do this because of the structure of my scripts.

Ideally, I would like to modify the function as follows:

def printusermessage(msg,verbose=True,log=None, gui=True): 
       if verbose == True: 
              print(msg)
       if gui == True: 
              # Update the TextArea value. 
       if not log == None: 
              # Save the msg in a log file. 

I know the simple solution, which is to use an Interval component and update the TextArea according to the log file. Unfortunately, the log file will be very long, so this solution will not be optimised for me.

So I am asking you to give me your ideas/solutions in my case.

Thank you in advance,

Alexis

PS: https://community.plotly.com/t/emulate-terminal-output-in-dcc-textarea-to-show-logging-details/44839 shows a similar problem.

Hello @AlexisInSAR,

Welcome to the community!

Can you not just import the function from the other file and then alter the print to a return and return the message?

If you need a length of time before you can return you can use a background callback.

Otherwise, what you could do it have a background callback that triggers the event and instead of having the other package return or print, it would write to a db that’s associated with the task. Once there is a valid response then the background callback would return the statement from the db.