使用pyinstaller将.py文件和.txt文件合并为.exe文件

4
我有一个Python程序,需要以两个文本文件作为输入。我已经使用PyInstaller将这个Python程序(.py文件)转换成了.exe文件,但是运行.exe文件时出现了FileNotFoundError错误。当.txt文件复制到.exe所在的路径时,程序可以正常运行。我的意图是不复制.txt文件,而是将.txt文件与.exe文件捆绑在一起,使.txt文件无法访问。我想将所有的.txt文件依赖项与.exe文件捆绑在一起,最终只需要一个.exe文件,在运行它时,应该与运行Python程序时一样工作。请建议我如何实现这一点。
我对PyInstaller很陌生。我曾尝试在.spec文件的数据参数中添加.txt文件。但是,这种方法无法将文本文件复制到我的.exe文件所在的dist文件夹中。但是,正如我之前提到的那样,我只需要单独的.exe文件。即使将.exe文件共享给其他人,他们也没有任何文本文件的访问权限,.exe文件也必须能够成功运行。
如下面的代码被添加到.spec文件中: 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'), ] 因此,我认为当您运行:pyinstaller spec_filename.spec时,readme_text_files将被复制到.exe文件所在的文件夹中。
1个回答

1

我希望将一个 .txt 文件和 .exe 文件捆绑在一起,因此我执行了以下操作:

  1. I edited the .spec file in the following way:

    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)
    

    Or simply you can directly include a directory itself like below:

    datas=[('C:/Users/njv5kor/eclipse-workspace/Trial/src/readme_text_files/','readme_text_files'),
                        ],
    
  2. In the python code i added the below code:

    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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接