使用Pyinstaller执行文件时,数据文件仅被暂时保存。

6
我用PyQt5创建了一个应用程序,并使用Pyinstaller进行了捆绑。该应用程序从存储在与启动应用程序的.py文件相同目录中的login.properties文件中加载登录信息。
此处所建议的那样,我正在使用以下函数修改路径:
import os, sys
# Translate asset paths to useable format for PyInstaller

def resource_path(relative_path):
  if hasattr(sys, '_MEIPASS'):
      return os.path.join(sys._MEIPASS, relative_path)
  return os.path.join(os.path.abspath('.'), relative_path)

它会创建一个名为_MEIPASS的临时文件夹,其中包含诸如我的login.properties之类的文件。

在应用程序中,我想使用以下函数保存login.properties信息:

self.loginFile = resource_path('./login.properties')    

def save_login_info(self):
        config = configparser.ConfigParser()
        config.read(self.loginFile)

        pw = self.login_ui.password_lineEdit.text()
        un = self.login_ui.username_lineedit.text()
        token = self.login_ui.token_lineEdit.text()
        alias = self.login_ui.gmail_alias_lineedit_2.text()
...     
            config.set('Login', 'password', pw )
            config.set('Login', 'username', un )
            config.set('Login', 'security_token', token )
            config.set('Login', 'alias', alias)

            with open(self.loginFile, 'w') as loginfile: 
                config.write(loginfile)

            print('Login info saved')

因此,更改的登录信息保存在临时文件/文件夹中,而不是保存在“原始”文件中。

有什么想法可以缓解这个问题吗?

2个回答

2

_MEIPASS 是一个临时文件夹。有时会使用条件 if hasattr(sys, '_MEIPASS') 来确定应用程序是运行自源代码还是构建后的。

不要将配置文件保存在 _MEIPASS 文件夹中。最好的做法是在用户目录下创建应用程序的文件夹。如果您运行的是开发版本(来自源代码),请在源代码目录中创建一个文件,否则请在用户目录中创建一个文件。

def get_config_path():
    if hasattr(sys, "_MEIPASS"):
        abs_home = os.path.abspath(os.path.expanduser("~"))
        abs_dir_app = os.path.join(abs_home, f".my_app_folder")
        if not os.path.exists(abs_dir_app):
            os.mkdir(abs_dir_app)
        cfg_path = os.path.join(abs_dir_app, "login.properties")
    else:
        cfg_path = os.path.abspath(".%slogin.properties" % os.sep)
    return cfg_path

当连接 abs_homef".my_app_folder" 时,在 "my_app_folder" 前面使用句点的作用是什么? - jack.py
1
@jack.py 会自动将文件夹在 Unix 系统中设为不可见。 - stilManiac

-1

我之前也遇到过同样的问题,似乎在--onefile模式下尝试写入或创建文件时,文件不会被保存。但是,可以通过在编译命令中包含数据文件来解决此问题:

C:\Users\user>pyinstaller myfile.py -F --add-data path/to/file/file.txt

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