Search code examples
pythonpython-3.xpython-3.6pythonw

pythonw 3.6.6 sys.stdout doing nothing on reassign


I am attempting to debug my pythonw script that I am writing because it sort of works when launching it through idle, but it crashes when launching it through cmd or double-clicking on it. the code i have at the moment that's failing is

import sys
sys.stdout = open("mylog.txt", "w")
sys.stderr = open("errors.txt", "w")
print("hello world")
import thisisgonnafail
print(sys.executable)

It does create the file, as I'm told by notepad++ that the files have been updated, but the files are both always empty, even though they should have the error message from the import that is set up to fail, and the print line


Solution

  • The code that you posted above should work. The problem that you are having is, most likely, with inspecting the file while the stream is still open. When using open() you always need to close the stream somehow. Untill you do this, the changes to the file won't be visible for you when inspecting it via other method (eg. manually opening a file).

    In this example, you can do it either by reassigning the sys.stdout and sys.stderr or by calling a close() (preferred method as it is more explicit and the intended way of handling streams) on them like this: sys.stdout.close().

    Also, be aware that if you will open and close them multiple times, you are better off using "a" for appending to the file, rather than rewriting the contents all the time.

    EDIT: You asked in comments about handling errors when doing stuff this way. The method that you suggested is correct, you can try/except the parts of code and have except close the stream.

    import sys
    sys.stderr = open("e.txt", "a")
    try:
        import nonexistingmodule
        print 'Should not be printed out'
    except:
        print 'Should be printed out'
        sys.stderr.close()
    

    This code above lets you test that the except path has been triggered.