Search code examples
pythonpexpectsys

How can I print the traceback and exception of a zmq.REQ worker?


I'm using pexpect.spawn to write some script that can run in parallel.

But I found that the traceback and exception of a zmq.REQ worker won't be printed out in the terminal where I run the master.py (zmq.REP).

I know sys.stderr can be used to redirect the traceback and exception, but I have no idea how should I use this in the worker.py so that the exceptions happen in worker.py can be printed out.


Solution

  • Use logging.exception and log into a file.

    Example:

    import logging
    
    logging.basicConfig(filename='example.log') 
    
    
    def fail():
        return 10/0
    
    try:
        fail()
    except Exception as err:
        loggin.exception(err)
    

    Output (example.log) :

    ERROR:root:integer division or modulo by zero
    Traceback (most recent call last):
      File "<ipython-input-4-d63f4b56d991>", line 2, in <module>
        fail()
      File "<ipython-input-3-edce7c179301>", line 2, in fail
        return 10/0
    ZeroDivisionError: integer division or modulo by zero