天天看點

python 生成exe檔案1、安裝pyinstaller2、打包python程式3、運作exe檔案4、外部檔案5、問題

大家好,又見面了,我是你們的朋友全棧君。

在windows下,可以使用pyinstaller打包python程式為exe可執行程式。

1、安裝pyinstaller

在cmd指令行視窗運作以下指令安裝pyinstaller

pip install pyinstaller           

複制

2、打包python程式

在python程式所在目錄,執行以下指令

# 切換到指定目錄
cd /d path
# 正常打包指令
pyinstaller -F -w -i ico_path xxx.py           

複制

  1. -F 是将所有檔案打成一個exe檔案,一般是必寫的(注意必須是大寫)
  2. -w 是程式運作時不顯示cmd界面
  3. -i 修改生成的exe檔案圖示,可以不寫(-i 不寫的話 ico_path也别寫)
  4. ico_path 是生成的exe檔案圖示位置
  5. py_path 是目标py檔案位置

3、運作exe檔案

打包完成後,在對應目錄會出現build和dist檔案夾,exe檔案就出現在dist檔案夾,直接運作即可。

4、外部檔案

以我的chromedriver為例

打包生成exe檔案後,依賴的檔案還有chromedriver和谷歌浏覽器(還需要版本一緻)

是以在生成exe檔案後,還需要将chromedriver和對應的谷歌浏覽器版本一起

5、問題

5.1、’pyinstall’ 不是内部或外部指令,也不是可運作的程式 或批處理檔案。

改為安裝pyinstaller

5.2、exe點開之後就出現failed to execute script xxx

  1. 存在中文路徑
  2. 使用pyinstaller時使用了-w指令與print沖突

5.3、反複運作本身

因為你開了程序,需要在main後面添加一句

multiprocessing.freeze_support()           

複制

5.4、Pyinstaller打包selenium去除chromedriver黑框問題

我的目錄是

C:\Users\45906\AppData\Local\Programs\Python\Python37\Lib\site-packages\selenium\webdriver\common\service.py           

複制

将其檔案中的75行修改

def start(self):
        """
        Starts the Service.

        :Exceptions:
         - WebDriverException : Raised either when it can't start the service
           or when it can't connect to the service
        """
        try:
            cmd = [self.path]
            cmd.extend(self.command_line_args())
            self.process = subprocess.Popen(cmd, env=self.env,
                                            close_fds=platform.system() != 'Windows',
                                            stdout=self.log_file,
                                            stderr=self.log_file,
                                            #修改前
                                            #stdin=PIPE)
                                            #修改後
                                            stdin=PIPE,creationflags=134217728)           

複制

這裡注意,是chromedriver的指令行黑框,并不是window本身的指令行,windows的黑框在你打包的時候添加-w即可

釋出者:全棧程式員棧長,轉載請注明出處:https://javaforall.cn/131113.html原文連結:https://javaforall.cn