Python 如何使用Pyinstaller-cx_Freeze executable sys.MEIPASS/sys.executable

Python 如何使用Pyinstaller-cx_Freeze executable sys.MEIPASS/sys.executable,python,executable,pyinstaller,cx-freeze,Python,Executable,Pyinstaller,Cx Freeze,我一直在为OSX El Capitan开发一个python可执行文件,我成功地使用Pyinstaller和cx_Freeze构建了该可执行文件,当我在另一台mac上实际运行该可执行文件时,问题就来了。我遇到的错误是无法找到主脚本中引用的.db文件,因此我查看了这两个程序的文档,发现sys.MEIPASS(Pyinstaller)和sys.executable(cx_Freeze)在--onefile应用程序中包含了数据文件。这是我在主脚本中使用的代码: def find_data_file(fi

我一直在为OSX El Capitan开发一个python可执行文件,我成功地使用Pyinstaller和cx_Freeze构建了该可执行文件,当我在另一台mac上实际运行该可执行文件时,问题就来了。我遇到的错误是无法找到主脚本中引用的.db文件,因此我查看了这两个程序的文档,发现sys.MEIPASS(Pyinstaller)和sys.executable(cx_Freeze)在--onefile应用程序中包含了数据文件。这是我在主脚本中使用的代码:

def find_data_file(filename):
    if getattr(sys, 'frozen', False):
        # The application is frozen
        datadir = os.path.dirname(sys._MEIPASS) #in cx_Freeze this is sys.executable     
    else:
        # The application is not frozen
        # Change this bit to match where you store your data files:
        datadir = ospath.abspath(os.pardir)

    return os.path.join(datadir, filename)

#This is how im using the "find_data_file" function in my code. 
dbpath = find_data_file('PubData.db')
conn = lite.connect(dbpath)
我在else语句中对它做了一些修改,以匹配我的项目目录的布局,当运行一个未冻结的应用程序时,它工作得非常好。 但是,当我尝试使用构建的可执行文件运行时,会出现无法找到.db文件的错误,我认为引用sys.MEIPASS或sys.executable可以解决这个问题

错误:

Traceback (most recent call last):
  File "interface/GUI.py", line 673, in <module>
  File "interface/GUI.py", line 82, in __init__
  File "interface/GUI.py", line 212, in getServerNames
sqlite3.OperationalError: no such table: servernames

如果有人能告诉我我做错了什么,或者给我一个解决方案,我将不胜感激

如果您试图访问在.spec文件中指定的任何数据文件,则必须在代码中使用Pyinstaller的_MEIPASS文件夹引用您的文件。下面是我如何处理名为Data.db的文件的:

import sys
import os.path

        if hasattr(sys, "_MEIPASS"):
            datadir = os.path.join(sys._MEIPASS, 'Data.db')
        else:
            datadir = 'Data.db'

        conn = lite.connect(datadir)
这取代了以下单行:

conn = lite.connect("Data.db")
这个链接很好地解释了这一点:

如果您试图访问在.spec文件中指定的任何数据文件,则必须在代码中使用Pyinstaller的_MEIPASS文件夹引用您的文件。下面是我如何处理名为Data.db的文件的:

import sys
import os.path

        if hasattr(sys, "_MEIPASS"):
            datadir = os.path.join(sys._MEIPASS, 'Data.db')
        else:
            datadir = 'Data.db'

        conn = lite.connect(datadir)
这取代了以下单行:

conn = lite.connect("Data.db")
这个链接很好地解释了这一点: