1

I have a pyinstaller executable (pyinstaller -F script.py) and .db file. Both in /home/dev/dist directory. This script can't find .db file despite it locates in the same directory. I figured out that script always runs from /home directory.

How to change path from /home to actually dir where the script runs from? I don't know whether it's macOS or pyinstaller feature.

P.S.: I don't need to add .db file to executable. It should be separate but in the same directory with script

MarianD
  • 13,096
  • 12
  • 42
  • 54
  • Possible duplicate of [Bundling data files with PyInstaller (--onefile)](https://stackoverflow.com/questions/7674790/bundling-data-files-with-pyinstaller-onefile) – Skandix Feb 11 '19 at 13:37

2 Answers2

0
import os

os.chdir("Your Path")

I don't know if this is what you are looking for but you can also try:


import glob

glob.glob("Your Path/*.db") #This will show all files with .db extension in path

And you can run .db file using list indexing

cocorocho
  • 35
  • 5
  • Ok but how to get real path? `os.path.dirname(os.path.realpath(__file__))` returns `/home`. Path is not static, it will vary from user to user – Kernel Panic Feb 11 '19 at 16:33
0

I had the same issue. It is not actually running in home directory, it is just harder to find the real directory for some reason after compiling in PyInstaller. The PyInstaller documentation suggests using the following in your code to get the real path:

    import sys, os
    if getattr(sys, 'frozen', False):
        # If the application is run as a bundle, the pyInstaller bootloader
        # extends the sys module by a flag frozen=True and sets the app
        # path into variable _MEIPASS'.
        dir_path = sys._MEIPASS
    else:
        dir_path = os.path.dirname(os.path.abspath(__file__))

Once you have the real path you can concatenate:

real_file_location = f'{dir_path}/my_file.db'

And that's it. Make sure when building your executable that you use the --add-data operator to specify what files your program will need. Example:

% pyinstaller --add-data my_file.db:. --add-data another_file.json:. /directory/to/your/code/script.py

These things should ensure that your PyInstaller executable can find the files it needs.