I have been trying to bundle a json file in a python executable created with pyinstaller. After a lot of researching, the solution I found involved making use of the _MEIPASS folder; however, VSCode claims that the sys package has no _MEIPASS member.
The relevant part of my code goes like this:
branches_path = 'bank_branches/bank_branches.json'
if hasattr(sys, "_MEIPASS"):
branches_path = os.path.join(sys._MEIPASS, branches_path)
The code works on the terminal version, as well as on the standalone application, so this is taken care of; however, I'd like to know if there is a solution which works and has no errors associated. If it helps, I'm using Python 3.6.6
1 Answer 1
I ran into a similar issue when creating an executable using pyinstaller. I had to make two changes to my script in order to get a functional executable.
First, I created this function:
def resource_path(relative_path):
try:
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
My script has several classes in it, so I put this at the very end, by itself, so that all classes could reference it. I then replaced any function I had that used
os.getcwd()
- which was probably a bad idea in the first place - with
resource_path()
and for the variable inside of resource_path() I used this function instead:
os.path.dirname(os.path.abspath(__file__))
This function returned what I wanted anyway; the location of THIS file/program that is running.
So, what previously was written like:
filePath = os.getcwd() + "\\my_file.csv"
Now reads as:
filePath = resource_path(os.path.dirname(os.path.abspath(__file__))) + "\\my_file.csv"
Once this was in place, my program compiled correctly and executed as expected, hopefully it can help you as well.