ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • pyinstaller로 .py 파일을 .exe로 만들기 (아이콘 추가,콘솔창 안뜨게,이미지 폴더 추가 )
    카테고리 없음 2021. 2. 3. 18:05

    쿠키런 킹덤이라는 모바일게임을 데스크탑 블루스택으로 하다보면 게임내 생산시설을 클릭하는 일을 자동화 하고 싶다는 생각은 누구나 드나보다.

    친구하나가 opepcv와 pygautogui로 매크로를 만들었길래 레퍼런스를 받아서 공유가능한 exe형태로 만들어봤다 (실재 공유 x)

     

    우선 친구가 만든 python파일을 중심으로 돌아가는 GUI를 PyQt5로 만들어 주었다.

    from info import *
    from MainWindow import *
    from PyQt5 import QtWidgets
    from sugar import *
    import os
    
    try:
        os.chdir(sys._MEIPASS)
        print(sys._MEIPASS)
    except:
        os.chdir(os.getcwd())
    
    class First(QtWidgets.QMainWindow, Ui_MainWindow) :
        def __init__(self) :
            super(First,self).__init__()
            self.setupUi(self)
    
            self.next_button.clicked.connect(self.nextButtonFunction)
    
    
        def nextButtonFunction(self):
            import cf
            for self.i, item in enumerate(self.CheckBoxList) :
                if item.isChecked():
                    cf.activationList[self.i]['activation'] = True
                    print('success')
                else:
                    print('False')
            self.cams = Second()
            self.cams.move(0,0)
            self.cams.show()
            self.close()
            print(cf.activationList)
    
    
    class Second(QtWidgets.QMainWindow,Second_) :
    
        def __init__(self):
            super(Second, self).__init__()
            self.setupUi(self)
            self.start.clicked.connect(self.start_button_function)
    
        def start_button_function(self):
            print('button pressed')
            print('instance set')
            start()
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        w = First()
        w.show()
        app.exec_()

     

    pyinstaller는 내가 exe로 만들고 싶은 매인 python파일에 import된 모든 모듈을 알아서 잘 처리해주므로

    (물론 오류가 발생할 수도 있고, 그럴 때는 hiddenimport관련 설정을 해줘야 한다고 한다. 나는 해당 오류가 없었지만)

     

    난 Qtdesigner로 만든 ui파일들을 모두 .py파일로 바꾼 후에 별로의 class에 상속시켜주는(Ui_MainWindow,Second_) 방법을 택했다.

    (pyinstaller가 익숙치 않아서 최대한 관련 설정을 피하고 싶었다. 찾아보니 ui파일을 포함하면서 exe로 바꾸는 설정도 있드라)

     

    pip install pyinstaller 후에 로컬 콘솔창에

    pyinstaller -F 파일이름.py

     하면 dist,build폴더와 .spec 파일이 만들어 진고, dist 폴더 안에 내가 exe파일이 있다.

     

    하지만 그냥 오류 없이 실행될리가 없지 역시 바로 오류가 났다.

    .png들을 img폴더안에 넣어 놨는데. 이것들의 경로를 찾을 수가 없단다. 이럴 땐 .spec파일의 수정이 필요하다

     

    참고로 오류 메세지를 보고 싶어도 콘솔창이 떳다가 금방 사라져서 보기가 힘든데, 그럴 땐 window powershell이나 git bash로 exe를 실행시켜 보면 된다.

    그리고 추후에 콘솔창이 뜨지 않게 하려면 --noconsole 을 추가하면 된다

    # -*- mode: python ; coding: utf-8 -*-
    
    block_cipher = None
    
    
    a = Analysis(['CookieFactory.py'],
                 pathex=['C:\\Users\\ted215\\Desktop\\projects\\me'],
                 binaries=[],
                 datas=[('./img/*', './img')],
                 hiddenimports=[],
                 hookspath=[],
                 runtime_hooks=[],
                 excludes=[],
                 win_no_prefer_redirects=False,
                 win_private_assemblies=False,
                 cipher=block_cipher,
                 noarchive=False)
    pyz = PYZ(a.pure, a.zipped_data,
                 cipher=block_cipher)
    exe = EXE(pyz,
              a.scripts,
              a.binaries,
              a.zipfiles,
              a.datas,
              [],
              name='CookieFactory',
              debug=False,
              bootloader_ignore_signals=False,
              strip=False,
              upx=True,
              upx_exclude=[],
              runtime_tmpdir=None,
              console=False,
              icon='C:\\Users\\ted215\\Desktop\\projects\\me\\cookie.ico')

     

    여튼 도망간 이미지들을 주워담아보려면 위 같은 .spec 파일에서 datas 안에 내가 원하는 이미지 파일들의 경로를 넣어주면 된다.  참조(developer-mistive.tistory.com/59)

     

    그리고 살펴보니 아이콘 추가, exe 이름변경, 콘솔창 숨기기등은 여기 spec의 exe 부분에서 할 수 있더라.

    icon에서 경로를 잡아주고 name란에 원하는 이름 적고, console에는 원하는 옵션 넣자.

     

    그리고 반드시(내가 이걸 안해서 30분을 삽질했다) 변경된 .spec 을 적용해서 exe를 새로 만들어야 하므로

    pyinstaller -F 파일이름.spec

    을 해주어야 dist 파일 안에 이미지파일들이 들어간 exe가 만들어진다. 

Designed by Tistory.