Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8592905
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T23:51:49+00:00 2026-06-11T23:51:49+00:00

The Problem I’ve been trying to write a program that logs uncaught exceptions and

  • 0

The Problem

I’ve been trying to write a program that logs uncaught exceptions and syntax errors for a subprocess. Easy, right? Just pipe stderr to the right place.

However, the subprocess is another python program- I’ll call it test.py– that needs to run as if its output/errors are not being captured. That is, running the logger program needs to seem like the user has just run python test.py as normal.

Further complicating the issue is the problem that raw_input actually gets sent to stderr if readline is not used. Unfortunately, I can’t just import readline, since I don’t have control over the files that are being run using my error logger.

Notes:

  • I am fairly restricted on the machines that this code will run on. I can’t install pexpect or edit the *customize.py files (since the program will be run by a lot of different users). I really feel like there should be a stdlib solution anyway though…
  • This only has to work on macs.
  • The motivation for this is that I’m part of a team researching the errors that new programmers get.

What I’ve Tried

I’ve tried the following methods, without success:

  • just using tee as in the question How do I write stderr to a file while using "tee" with a pipe? (failed to produce raw_input prompts); python implementations of tee that I found in several SO questions had similar issues
  • overwriting sys.excepthook (failed to make it work for a subprocess)
  • this question’s top answer seemed promising, but it failed to display raw_input prompts correctly.
  • the logging module seems useful for actually writing to a log file, but doesn’t seem to get at the crux of the issue
  • custom stderr readers
  • endless googling
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T23:51:51+00:00Added an answer on June 11, 2026 at 11:51 pm

    Based on @nneonneo ‘s advice in the question comments, I made this program that seems to get the job done. (Note that currently, the name of the logger file has to by “pylog” for the errors to be printed correctly to the end user.)

    #!/usr/bin/python
    
    '''
    This module logs python errors.
    '''
    
    import socket, os, sys, traceback
    
    def sendError(err):
        # log the error (in my actual implementation, this sends the error to a database)
        with open('log','w') as f:
            f.write(err)
    
    
    def exceptHandler(etype, value, tb):
        """An additional wrapper around our custom exception handler, to prevent errors in
           this program from being seen by end users."""
        try:
            subProgExceptHandler(etype, value, tb)
        except:
            sys.stderr.write('Sorry, but there seems to have been an error in pylog itself. Please run your program using regular python.\n')
    
    def subProgExceptHandler(etype, value, tb):
        """A custom exception handler that both prints error and traceback information in the standard
           Python format, as well as logs it."""
        import linecache
    
        errorVerbatim = ''
    
        # The following code mimics a traceback.print_exception(etype, value, tb) call.
        if tb:
            msg = "Traceback (most recent call last):\n"
            sys.stderr.write(msg)
            errorVerbatim += msg
    
            # The following code is a modified version of the trackeback.print_tb implementation from
            # cypthon 2.7.3
            while tb is not None:
                f = tb.tb_frame                                                      
                lineno = tb.tb_lineno                                                  
                co = f.f_code                                                        
                filename = co.co_filename                                              
                name = co.co_name
                # Filter out exceptions from pylog itself (eg. execfile).
                if not "pylog" in filename:
                    msg = '  File "%s", line %d, in %s\n' % (filename, lineno, name)
                    sys.stderr.write(msg)       
                    errorVerbatim += msg
                    linecache.checkcache(filename)                                         
                    line = linecache.getline(filename, lineno, f.f_globals)                
                    if line: 
                        msg = '    ' + line.strip() + '\n'
                        sys.stderr.write(msg)
                        errorVerbatim += msg
                tb = tb.tb_next                                           
    
        lines = traceback.format_exception_only(etype, value)
        for line in lines:
            sys.stderr.write(line)
            errorVerbatim += line
    
        # Send the error data to our database handler via sendError.
        sendError(errorVerbatim)
    
    def main():
        """Executes the program specified by the user in its own sandbox, then sends
           the error to our database for logging and analysis."""
        # Get the user's (sub)program to run.
        try:
            subProgName = sys.argv[1]
            subProgArgs = sys.argv[3:]
        except:
            print 'USAGE: ./pylog FILENAME.py *ARGS'
            sys.exit()
    
        # Catch exceptions by overriding the system excepthook.
        sys.excepthook = exceptHandler
        # Sandbox user code exeuction to its own global namespace to prevent malicious code injection.
        execfile(subProgName, {'__builtins__': __builtins__, '__name__': '__main__', '__file__': subProgName, '__doc__': None, '__package__': None})
    
    if __name__ == '__main__':
        main()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Problem: Write a program that prompts the user to enter some number of 1,
Problem occured when i tried to display xml data that has been taken by
Problem: Trying to create a Mix that is applied to the AVPlayerItem, but it
Problem: Been struggling to get my code to load external shaders and it is
Problem: I have a table that prints out vertical but I would like it
Problem: I am trying to build a recursive tree using a function and data
Problem: I'm working on a website where there is a dial that displays a
Problem: I have 2 classes, DB class and a User class, that will work
Problem: I wrote a hello world java program, compiled and created a jar file
Problem Description: Multi-player Game that works over the some kind of network, in game

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.