Search code examples
pythondistutilssetup.py

Saving the installation log generated from setup.py


Is there a way to save the output that is generated during the installation of a program being installed using setup.py ? I want to write this into the setup.py script itself, not in the terminal when i run setup.py


Solution

  • Before the setup() function is called, redirect sys.stdout ( and sys.stderr to the log file. )

    Make sure you revert back the stdout ( and stderr ) to their default references and print the contents of log file to stdout as well.

    Your setup.py should look like this:

    from setuptools import setup, find_packages
    import sys
    
    stdout = sys.stdout
    stderr = sys.stderr
    
    log_file = open('log', 'w')
    sys.stdout = log_file
    sys.stderr = log_file
    
    setup ( 
            ...  ,
            ...
          )
    
    # Make sure to close the log file. You could also use with to surround the setup()
    # To ensure log file is closed in the event of exception.
    log_file.close()
    
    sys.stdout = stdout
    sys.stderr = stderr
    
    with open('log', 'r') as log_file:
        sys.stdout.write(log_file.read())