본문 바로가기
파이썬

파이썬 `with open (...)`과`sys.stdout`을 모두 멋지게 처리하는 방법은 무엇입니까?

by º기록 2021. 1. 13.
반응형

종종 데이터를 파일로 출력하거나 파일이 지정되지 않은 경우 표준 출력으로 출력해야합니다. 다음 스 니펫을 사용합니다.

if target:
    with open(target, 'w') as h:
        h.write(content)
else:
    sys.stdout.write(content)

다시 작성하고 두 대상을 균일하게 처리하고 싶습니다.

이상적인 경우는 다음과 같습니다.

with open(target, 'w') as h:
    h.write(content)

하지만 with 블록을 떠날 때 sys.stdout이 닫히고 원하지 않기 때문에 이것은 잘 작동하지 않습니다. 나는 원하지 않는다

stdout = open(target, 'w')
...

원래 stdout을 복원하는 것을 기억해야하기 때문입니다.

관련 :



수정


 

해결 방법

 

여기 상자 밖에서 생각하면 사용자 정의 open () 메서드는 어떻습니까?

import sys
import contextlib

@contextlib.contextmanager
def smart_open(filename=None):
    if filename and filename != '-':
        fh = open(filename, 'w')
    else:
        fh = sys.stdout

    try:
        yield fh
    finally:
        if fh is not sys.stdout:
            fh.close()

다음과 같이 사용하십시오.

# For Python 2 you need this line
from __future__ import print_function

# writes to some_file
with smart_open('some_file') as fh:
    print('some output', file=fh)

# writes to stdout
with smart_open() as fh:
    print('some output', file=fh)

# writes to stdout
with smart_open('-') as fh:
    print('some output', file=fh)

 

참조 페이지 https://stackoverflow.com/questions/17602878

 

 

반응형

댓글