簡體   English   中英

使用pyinstaller將.py文件和.txt文件合並到.exe文件中

[英]Merging .py file and .txt files into .exe file using pyinstaller

我有一個 python 程序,它接收兩個文本文件作為輸入。 我已使用 pyinstaller 將此 python 程序(a.py 文件)轉換為 a.exe 文件。 運行時.exe 文件給出 FileNotFoundError。 但是,當 .txt 文件被復制到 .exe 所在的路徑時,它可以正常工作。 我的意圖是不復制 .txt 文件,而是將 .txt 文件與 .exe 捆綁在一起,這樣 .txt 文件就無法訪問。 All.txt 文件依賴項 我想將它與.exe 捆綁在一起,最終應該只有一個.exe 文件,當我運行它時,它應該與我運行 python 程序時的工作方式相同。 請建議我實現相同目標的方法

我是 pyinstaller 的新手。 我曾嘗試將 .txt 文件添加到 .spec 文件中的數據參數。 但這無法將文本文件復制到 my.exe 所在的 dist 文件夾中。 但正如我所提到的,我只需要單獨的 .exe 文件。 即使將 .exe 文件共享給無權訪問任何文本文件的其他人,該 .exe 也必須成功運行

a.datas+=[('D:/Trial/src/readme_text_files/readme1.txt','readme_text_files/readme1.txt','readme_text_files'), ('D:/Trial/src/readme_text_files/readme2.txt', 'readme_text_files/readme2.txt','readme_text_files'), ]

上面的代碼已添加到 .spec 文件中,因此我假設 readme_text_files 必須復制到運行時存在的文件夾中:pyinstaller spec_filename.spec

我希望將 .txt 文件與 .exe 文件捆綁在一起,因此我執行了以下操作:

  1. 我通過以下方式編輯了 .spec 文件:

     a = Analysis(['mainProgram_edited_for_datas.py'], pathex=['D:\\Trial\\src'], binaries=[], datas=[ ('D:/Trial/src/readme_text_files/readme1.txt','readme_text_files'), ('D:/Trial/src/readme_text_files/readme2.txt','readme_text_files'), ], ...........(Rest of the.spec file contents as it is)

    或者只是你可以直接包含一個目錄本身,如下所示:

     datas=[('C:/Users/njv5kor/eclipse-workspace/Trial/src/readme_text_files/','readme_text_files'), ],
  2. 在 python 代碼中,我添加了以下代碼:

     def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") return os.path.join(base_path, relative_path) file = resource_path("readme_text_files\\readme1.txt")

基本上,pyinstaller 將 .txt 文件捆綁到 .py 文件並創建單個.exe 有關 _MEIPASS 的詳細信息,請參閱鏈接: https://pyinstaller.readthedocs.io/en/v3.3.1/operating-mode.html#how -the-one-file-program-works

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM