본문 바로가기
개발

파이썬 pyinstaller 실행 후 'NoneType' object has no attribute 'write'

by 정보알려주는언니 2023. 1. 14.

요즘 파이썬으로 이것저것 개발을 하고 있다. 

pyqt5를 통해 ui를 만들고, 실시간으로 로그를 출력하는 기능을 만들었다.

파이썬으로 디버깅시에는 문제없이 동작하지만 아래와같은 오류가 발생했다.

 

'NoneType' object has no attribute 'write'

 

 

 

정말 오랜만에 자살충동이 일어났다^^.. 

스택오버플로우에서 관련 내용을 찾았고, 한국사이트는 잘 안나오는것같길래

나와같은 오류가 발생하는 사람들을 위해 적어보겠다. 

 

 

실시간 로그 출력 기능

일단 아래 사이트를 참고하여 실시간 로그 출력이 가능한 기능을 구현했었다.

 

[pyqt5] how to redirect stdout to textbrowser / textedit

파이썬에서 stdout을 pyqt5 로 리다이렉션 하는 법을 설명 드리겠습니다. 크게 요약드리자면 sys.stdout.write를 textBrowser의 insertPlainText 메소드로 연결 시키는 방법입니다. 우선 아래 처럼 StdoutRedirect 클

4uwingnet.tistory.com

 

StdoutRedirect라는 클래스를 생성하여 print 명령어가 실행되는 타이밍에 console창에 출력되는 내용을 textBrowserLog에 출력하는 기능이다.

 

 

오류

pyinstaller를 통해 exe파일을 만들었는데, 아래와같은 오류가 발생했다. 

'NoneType' object has no attribute 'write'

 

 

발생원인분석 & 해결방안

발생되는 이유는 exe파일 실행시 noconsole옵션을 추가했는데, console창이 없기때문에 stdout.write 함수를 실행할 수 없다는 내용이다.

 

 

StdoutRedirect 클래스에 위와같은 class를 추가했다.

 

class LoggerWriter:
    def __init__(self, level):
        # self.level is really like using log.debug(message)
        # at least in my case
        self.level = level

    def write(self, message):
        # if statement reduces the amount of newlines that are
        # printed to the logger
        if message != '\n':
            self.level(message)

    def flush(self):
        # create a flush method so things can be flushed when
        # the system wants to. Not sure if simply 'printing'
        # sys.stderr is the correct way to do it, but it seemed
        # to work properly for me.
        self.level(sys.stderr)

위 클래스를 추가한뒤, StdoutRedirect __init__시 self.stdout 호출 전에 아래와같이 추가를 했다. 

        sys.stdout = LoggerWriter(logging.debug)
        sys.stderr = LoggerWriter(logging.warning)

참고한 코드는 아래와같다.

 

 

CX_FREEZE Window - AttributeError: 'NoneType' object has no attribute write

I am currently using cx_freeze 6.1 (had some different issues with 6.2 and 6.3) to generate MSI windows installer for an OpenCV python application. Compilation was successful and generated MSI inst...

stackoverflow.com

 


댓글