본문 바로가기

프로그래밍/파이썬

[ Python ] Selenium 사용 시, console 제거 방법

728x90
반응형

 

문제 : Python의 pyinstaller를 이용하여, Selenium을 사용하는 실행 프로그램을 생성할 때, console이 제거되지 않는 문제.

1. 해결방안 ( Selenium 패키지 내부 수정 )

  • Selenium 버전 : 4.11.2 기준
  • 가상환경/site-packages/selenium/webdriver/common/service.py 파일로 이동한다.
  • 아래와 같은 코드가 있음
    def _start_process(self, path: str) -> None:
        """Creates a subprocess by executing the command provided.

        :param cmd: full command to execute
        """
        cmd = [path]
        cmd.extend(self.command_line_args())
        close_file_descriptors = self.popen_kw.pop("close_fds", system() != "Windows")
        try:
            self.process = subprocess.Popen(
                cmd,
                env=self.env,
                close_fds=close_file_descriptors,
                stdout=self.log_output,
                stderr=self.log_output,
                stdin=PIPE,
                creationflags=self.creation_flags,
                **self.popen_kw,
            )
            logger.debug(f"Started executable: `{self._path}` in a child process with pid: {self.process.pid}")
        except TypeError:
            raise
        except OSError as err:
            if err.errno == errno.EACCES:
                raise WebDriverException(
                    f"'{os.path.basename(self._path)}' executable may have wrong permissions."
                ) from err
            raise

 

  • try문 내부에 있는 self.process = subprocess.Popen 부분에 creationflags의 매개변수값을 설정하는 self.creation_flags의 값을 아래 처럼 변경
  • from win32process import CREATE_NO_WINDOW 를 통해 CREATE_NO_WINDOW 를 가져와서
  • try문 내부에 self.creation_flags = CREATE_NO_WINDOW 를 선언하여 준다.
    def _start_process(self, path: str) -> None:
        """Creates a subprocess by executing the command provided.

        :param cmd: full command to execute
        """
        from win32process import CREATE_NO_WINDOW
        cmd = [path]
        cmd.extend(self.command_line_args())
        close_file_descriptors = self.popen_kw.pop("close_fds", system() != "Windows")
        try:
            self.creation_flags = CREATE_NO_WINDOW
            self.process = subprocess.Popen(
                cmd,
                env=self.env,
                close_fds=close_file_descriptors,
                stdout=self.log_output,
                stderr=self.log_output,
                stdin=PIPE,
                creationflags=self.creation_flags,
                **self.popen_kw,
            )
            logger.debug(f"Started executable: `{self._path}` in a child process with pid: {self.process.pid}")
        except TypeError:
            raise
        except OSError as err:
            if err.errno == errno.EACCES:
                raise WebDriverException(
                    f"'{os.path.basename(self._path)}' executable may have wrong permissions."
                ) from err
            raise
  • 그 이후, pyinstaller 하게 되면 더이상 console 창이 나타나지 않는다.
  • 예시 명령 ) pyinstaller --noconsole --onefile main.py
    • --noconsole은 pyinstaller를 실행하였을 때 나타나는 별도의 console 창이 호출되지 않도록 하는 설정이다.
    • 본 게시물의 selenium webdriver를 구동 시, 호출되는 console과는 별계로 작동한다는 점 알아두시면 됩니다.
  • 굳이 from win32process import CREATE_NO_WINDOW를 선언하여야 한다면 대답은 "NO" 입니다.
  • 저렇게 하는 이유는, 단순 보기 좋기 때문입니다.
  • 다른 방법으로는 아래 처럼도 할 수 있습니다.
self.creation_flags = 0x08000000
  • 하지만 별로 직관적이지도 않고, 예쁘지 않죠? 그래서 그렇습니다.
728x90
반응형