【问题标题】:PyInstaller: problems on update a json file from an EXE program file (-in the next relunch, json file it's not been update)PyInstaller:从 EXE 程序文件更新 json 文件的问题(-在下一次重新启动中,json 文件尚未更新)
【发布时间】:2016-10-05 00:26:29
【问题描述】:

我正在测试一个由 py​​installer 制作的 EXE。 在项目文件夹中有一个名为 config 的文件夹,其中包含一个 json 文件,用户在其中存储他想要的所有信息 - 对于使用 tkinter 的 GUI im - 但最后在我重新启动此应用程序并重新打开 json 文件后,它出现了原始文件。

我读到要在执行时创建一个新文件夹,其中放置了原始 json 文件。但我对这个解决方案不太满意。

任何帮助将不胜感激

更新:

这是项目结构:

/config
      |----config.json
/modules
      |----admin
      |----core
      |----graphwo
init.py

代码执行良好,除了我希望用户将他们的信息保存在 config.json 文件中,换句话说,在执行时间。但是因为我使用的 PyInstaller 是 --onefile 不允许更新 config.json 文件

更新二:

我还有这段代码,它在每个文件的执行时获取当前路径——图像、数据和 json 文件——应用程序需要:

def getPathFileAtExecution(relative):
    try:
    base_path = sys._MEIPASS
except Exception:
    base_path = os.path.abspath(".")
return os.path.join(base_path, relative)

当程序调用 json 文件进行读写时,我会跟踪程序的任何步骤。但是在它完成并重新启动后,之前所做的所有更改都不会反映。 现在五月更清楚了吗?

【问题讨论】:

    标签: python json pyinstaller


    【解决方案1】:

    首先检查您是否指向正确的路径。某些操作系统对某些系统变量和函数调用的响应不同。

    import sys
    import os
    if getattr(sys,'frozen',False):
        current_path = os.path.dirname(sys.executable)
    else:
        current_path = os.path.dirname(os.path.realpath(__file__))
    
    config_json_file_path = os.path.join(current_path, 'config', 'config.json')
    print config_json_file_path
    

    【讨论】:

      【解决方案2】:
      import os
      import sys
      if getattr(sys, 'frozen', False):
          # we are running in a |PyInstaller| bundle
          base_path = sys._MEIPASS
          extDataDir = os.getcwd()
          print base_path
          print extDataDir
      else:
          # we are running in a normal Python environment
          base_path = os.getcwd()
          extDataDir = os.getcwd()
      

      sys._MEIPASS 变量是在程序运行时运行应用程序捆绑文件的位置。这与您的应用程序所在的位置不同。为了让您的程序找到并操作该非捆绑的 .json 文件,我使用了os.getcwd() 来获取您的应用程序所在的文件夹。

      os.getcwd() 获取可执行文件所在的当前工作目录。然后,如果您的 .json 文件位于名为 config 的文件夹中,并且该文件夹位于运行 exe 的当前工作目录中,你会使用

      ext_config = os.path.join(extDataDir, 'config', 'your.json')

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多