2017-01-26 34 views
0

我有一個工作的Python腳本3,inventoryScraper.py,我試圖使成1個文件的可執行我可以分發。我一直在Python 3中使用Pyinstaller 3,它已經在過去。我有一個文件'Store_Codes.csv',腳本需要運行,我希望它包含在可執行文件中。Pyinstaller 3個添加數據文件與--onefile

我已閱讀並嘗試所有與此以前的答案,但沒有奏效/我把事情搞糟了。當Store_Codes.csv與exe文件位於同一文件夾中時,生成的.exe文件可以正常工作,但不會以其他方式執行。我絕對是一個新手,Python,但我給這人有任何與命令行或任何相關的經驗,所以它是一個全功能於一身的文件是非常重要的。

我修改了我在其他帖子上看到的各種方式的spec文件,沒有任何工作,我相信我是誤解,我真的可以使用幫助。

有什麼直接的方式,與Pyinstaller 3,包括在onefile EXE數據文件?

謝謝!

回答

0

那麼有實際上是最簡單的一種變通,重命名Store_Codes.csvStore_Codes.py然後編輯該文件:

csv_codes = """ 

csv file content... 

""" 

在主腳本:import Store_Codes然後csv_file_content = Store_Codes.csv_codes

然後在pyinstaller使用--onefile,它會自動將Store_Codes.py包括到您新生成的exe文件中。

P.S.如果是CSV文件utf-8編碼的內容,不要忘了# -*- coding: utf-8 -*-

+0

我沒有完全按照你寫的,但我得到一個「導入錯誤:沒有名爲‘編號(store_code)’模塊」 – Clive

+0

你把'Store_Codes。py'與主腳本放在同一個文件夾中? – Shane

+0

我做了,它仍然給我一個錯誤,我只是測試了主腳本,它的工作原理應該如此。 – Clive

0
  1. Store_Codes.csv在同一文件夾中.py文件。
  2. 在.spec文件中的字段data添加datas=[('Store_Codes.csv', '.')],
  3. 你應該添加到您的.py文件

    if getattr(sys, 'frozen', False): 
        # if you are running in a |PyInstaller| bundle 
        extDataDir = sys._MEIPASS 
        extDataDir = os.path.join(extDataDir, 'Store_Codes.csv') 
        #you should use extDataDir as the path to your file Store_Codes.csv file 
    else: 
        # we are running in a normal Python environment 
        extDataDir = os.getcwd() 
        extDataDir = os.path.join(extDataDir, 'Store_Codes.csv') 
        #you should use extDataDir as the path to your file Store_Codes.csv file 
    
  4. 編譯文件。

討論

當您啓動它創建爲操作系統相應的臨時文件夾位置的臨時文件夾中.exe。該文件夾名爲_MEIxxxxxx,其中xxxxxx是一個隨機數。你需要運行該腳本將在那裏 的sys._MEIPASS是這個臨時文件夾的路徑中的所有文件。

當您添加datas=[('Store_Codes.csv', '.')]到您的規範文件。它會將文件複製到軟件包的主文件夾。如果你想保持它組織,你可以創建一個使用datas=[('Store_Codes.csv', 'another_folder')]不同的文件夾,然後在你的代碼,你將有

if getattr(sys, 'frozen', False): 
    # if you are running in a |PyInstaller| bundle 
    extDataDir = sys._MEIPASS 
    extDataDir = os.path.join(extDataDir,another_folder, 'Store_Codes.csv') 
    #you should use extDataDir as the path to your file Store_Codes.csv file 
else: 
    # we are running in a normal Python environment 
    extDataDir = os.getcwd() 
    extDataDir = os.path.join(extDataDir,another_folder 'Store_Codes.csv') 
    #you should use extDataDir as the path to your file Store_Codes.csv file 
相關問題