Python: Pyinstaller on mac Current directory issues

Python: Pyinstaller on mac Current directory issues … here is a solution to the problem.

Python: Pyinstaller on mac Current directory issues

I

created a small script that I want to run as an executable on Mac and Windows.

I use –

-onefile to create the executable as a file, and I want to use a file that is in the same directory as the executable.

In Windows, os.getcwd() works fine with pyinstaller, but on Mac it reverts to the base path:

> /Users/User
Traceback (most recent call last):
  File "test.py", line 93, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '/Users/user/Invoices/'
[62121] Failed to execute script test
logout

When I run it as a .py file, it also gets the correct directory on my Mac.

I’ve tried changing os.getcwd() to os.path.realpath(__file__) but it still gives the wrong path when using pyinstaller conversions.

I want to be able to move the executable on my Mac and use whatever directory it is in.

Solution

As it turns out, the following works:

dir_path = slash.join(sys.argv[0].split(slash)[:-1])

This only works when using an executable file on your Mac. I still use os.getcwd on Windows, and the same goes for running python scripts.

Related Problems and Solutions