민서네집

python 프로그램 redirect 시 파일 쓰기 지연의 해결책 본문

Python

python 프로그램 redirect 시 파일 쓰기 지연의 해결책

브라이언7 2018. 1. 26. 01:00

python 프로그램을 Windows 운영체제의 명령 프롬프트에서 실행하면서 redirect 시켜서 파일에 저장할 때 쓰기가 지연되는 문제가 있다.


성능을 위해서 일부러 그랬을텐데, tail 프로그램으로 로그를 확인하는데는 매우 불편했다.


여기에 대해서 해결책을 몇가지 찾았다.



For every iteration, you must add this.

sys.stdout.flush()


A simple solution is to add a -u option for python command to force unbuffered stdin, stdout and stderr.

python -u myscript.py > myscript.log 2>&1




You should pass flush=True to the print function:

import time

for i in range(10):
    print('bla', flush=True)
    time.sleep(5)

According to the documentation, by default, print doesn't enforce anything about flushing:

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

And the documentation for sys's strems says:

When interactive, standard streams are line-buffered. Otherwise, they are block-buffered like regular text files. You can override this value with the -u command-line option.


If you are stuck with an ancient version of python you have to call the flush method of the sys.stdout stream:

import sys
import time

for i in range(10):
    print('bla')
    sys.stdout.flush()
    time.sleep(5)


명령 프롬프트에서 python -h 해서 옵션을 보면


-u     : force the binary I/O layers of stdout and stderr to be unbuffered;

         stdin is always buffered; text I/O layer will be line-buffered;

         also PYTHONUNBUFFERED=x


라고 나와 있다.


sys.stdout.flush()

라고 해서 stdout 은 flush 할 수 있지만, stderr 도 flush 되게 하기 위해선,

python 실행 시 -u 옵션을 주는 것이 좋을것 같다.


C:\python>python -u agent.py --train > agent.log 2>&1


'Python' 카테고리의 다른 글

Jupyter notebook 테마(theme) 적용하기  (0) 2019.01.21
Python for Econometrics  (0) 2018.06.13
MIT 6.00 컴퓨터 공학과 프로그래밍(Python) 오픈 코스  (0) 2016.12.06
[Python] Function Argument  (0) 2016.11.18
jupyter notebook markdown  (0) 2016.10.30
Comments