如何将信息加载到pyinstaller可执行文件

2024-10-02 20:37:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,正在尝试开发解决方案。下面是我目前陷入困境的场景


背景

我有两个文件都在同一个目录中

  1. actualcode.py
  2. userInformation.py

userInformation.py有一些用户可以手动更改的数据。 actualcode.pyuserInformation.py加载数据并对其进行处理并给出输出

执行将以这种方式进行,用户在userInformation.py中输入数据并保存它,然后运行actualcode.py并获得输出


发行

我想为actualcode.py创建一个可执行文件,我可以使用命令:pyinstaller --onefile actualcode.py

但是,在构建exe时,pyinstaller也会加载userInformation.py文件并将其与可执行文件捆绑在一起,因此现在即使用户对userInformation.py文件进行了更改,在运行actualcode.py时也不会加载/反映这些更改,因为该文件已加载到exe

我想知道有没有更好的办法

将数据加载到dotenv文件而不是userInformation.py会解决我的问题吗

或者pyinstaller中是否有任何参数可以帮助我在actualcode.py上构建可执行文件并仍然从userInformation.py加载数据

还有没有一种方法可以用python构建一个参数化的exe?在这种情况下,我会用数据参数调用exe,而不是使用其他文件


Tags: 文件数据用户py目录可执行文件参数场景
2条回答

如果不想使用JSON,就不必使用JSON。您只需更改userInformation.py脚本即可将所有信息保存在.txt文件中。并更改actualcode.py脚本以从.txt文件中获取信息。您必须创建两个.exe文件。一个用于操纵用户信息和实际文件,以执行某些操作

希望有帮助

例如,使用JSON,而不是使用python脚本本身作为数据存储的手段

这里有一些你可以玩的示范

import json
from pprint import pprint

relative_loc = "./file_data.json"


def write():
    # create some data to save
    some_list = [i for i in range(3)]
    some_dict = {i: n for i, n in enumerate(range(0, 6, 2))}
    some_name = [i * 2 for i in 'abcd']

    to_file = {"list": some_list,
               "dict": some_dict,
               "name": some_name}
    
    # saving to json
    with open(relative_loc, 'w') as f:
        json.dump(to_file, f, indent=2)


def read():
    # reading json
    with open(relative_loc, 'r') as f:
        file = json.load(f)
    
    # Do something to file - just printing for this demo.
    pprint(file)


write()
read()

文件输出:

{
  "list": [
    0,
    1,
    2
  ],
  "dict": {
    "0": 0,
    "1": 2,
    "2": 4
  },
  "name": [
    "aa",
    "bb",
    "cc",
    "dd"
  ]
}

读取结果:

{'dict': {'0': 0, '1': 2, '2': 4},
 'list': [0, 1, 2],
 'name': ['aa', 'bb', 'cc', 'dd']}

Process finished with exit code 0

要添加,如果您计划使用带有 onefile标志的PyInstaller,则在执行时会得到一个打包的exe,该exe将解压缩到临时目录

这使得工作目录变成临时目录。如果是这样的话,所有的相对路径都将被打断

这是问题的实际原因,即在userInformation.py上所做的更改没有反映出来-因为每次运行onefile exe时,都会在临时目录下解压其中的userInformation.py

如果要使用onefile选项,则需要如下更改工作目录:

def IsFrozen():
    """
    Checks whether Python instance is Frozen(aka onefile) or not.
    Change directory if needed.
    """
    if getattr(sys, "frozen", False):
        return

    file_dir = os.path.dirname(sys.argv[0])
    
    try:
        os.chdir(file_dir)
    except OSError:  # Fail-safe
        pass

通过这种方式,您的脚本将找到放置在exe文件中的文件,但不会找到总是在所谓的"import time"上导入的模块

相关问题 更多 >