Tian
Tian

Reputation: 980

Windows only writes to file after process is stopped

I wrote a really simple script to test out the redirection of windows machine stdout. The program is as such

# hw.py
def main():
    print('Hello World')
    import time
    time.sleep(1000)

if __name__ == '__main__':
    main()

I ran this script using the following command.

python3 hw.py > hw.log

By observing in real time hw.log using either tail -f on git bash or opening an emacs buffer, I noticed that 'Hello World' is only printed to hw.log when the process ends, or it is cancelled prematurely.


This means that I cannot have a live view of a program output while writing it to a file. Worst still, if my program consists of infinite child processes, any output from the program will not be written to the file

How do I resolve this?

Upvotes: 1

Views: 123

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32294

To force the Python stdout and stderr streams to be unbuffered you can pass the -u argument.

python3 -u hw.py > hw.log

Setting the environment variable PYTHONBUFFERRED=1 will have the same effect

Upvotes: 4

Related Questions