使用onefile选项在Pyinstaller中添加数据文件

Ahm*_*Was 3 python pyinstaller python-3.x python-3.6

我正在尝试将图像添加到Pyinstaller生成的一个文件中。我读过很多这样的问题/论坛,一个一个和它仍然不工作。

我知道对于一个文件操作,Pyinstller会生成一个temp文件夹,可以通过来访问sys.MEIPASS。但是我不知道我应该在脚本的确切位置添加此内容 sys.MEIPASS

请显示以下内容:

1- 在何处以及如何 sys.MEIPASS添加?在python脚本中,还是在spec文件中?

2-使用的确切命令是什么?我试过了

pyinstaller --onefile --windowed --add-data="myImag.png;imag" myScript.py
Run Code Online (Sandbox Code Playgroud)

要么

pyinstaller --onefile --windowed myScript.py
Run Code Online (Sandbox Code Playgroud)

然后将('myImag.png','imag')添加到规格文件中,然后运行

pyinstller myScript.spec
Run Code Online (Sandbox Code Playgroud)

没有一个工作。

注意:我在Windows 7下有python 3.6

Jam*_*mes 9

当使用PyInstaller打包为单个文件时,运行.exe将把所有文件解压缩到TEMP目录中的文件夹中,运行脚本,然后丢弃这些临时文件。每次运行时,临时文件夹的路径都会更改,但是会将其位置的引用添加到sysas中sys._MEIPASS

要利用此功能,当您的Python代码读取也会打包到.exe中的任何文件时,您需要将文件位置更改为sys._MEIPASS。换句话说,您需要将其添加到您的python代码中。

这是一个示例,该示例使用您引用的链接中的代码将文件路径打包到单个文件时,将文件路径调整为正确的位置。

# data_files/data.txt
hello
world

# myScript.py
import sys
import os

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

def print_file(file_path):
    file_path = resource_path(file_path)
    with open(file_path) as fp:
        for line in fp:
            print(line)

if __name__ == '__main__':
    print_file('data_files/data.txt')
Run Code Online (Sandbox Code Playgroud)

使用以下选项运行PyInstaller将文件打包:

pyinstaller --onefile --add-data="data_files/data.txt;data_files" myScript.py
Run Code Online (Sandbox Code Playgroud)

构建myScript.exe,它可以正常运行,并且可以打开和读取打包的数据文件。


小智 6

我尝试更改 python 脚本的工作目录,它似乎有效:

import os 
import sys

os.chdir(sys._MEIPASS)
os.system('included\\text.txt')
Run Code Online (Sandbox Code Playgroud)

我的 pyinstaller 命令:

pyinstaller --onefile --nowindow --add-data text.txt;included winprint.py --distpath .
Run Code Online (Sandbox Code Playgroud)