Search code examples
pythonworking-directory

Get python .exe path


I made a program with python that runs correctly when run with python interpreter. It reads some files from the same directory. In order to run the script from other paths, the script changes its working directory to its own location.

import os
abspath = os.path.realpath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

But this does not work when I package it to .exe. Because when running .exe the __file__ variable is "main.py".

I know that it can be fixed by explicitly setting a fixed path:

os.chdir('/Fixed/Path')

But is there an elegant solution?


Solution

  • So the answer here is actually in two parts. To get the executable's location, you can use

    import sys
    exe = sys.executable
    

    To then chdir to the directory of the executable, you should try something like

    import os
    import sys
    
    exe = sys.executable
    dname = os.path.dirname(exe)
    os.chdir(dname)
    

    or simply

    os.chdir(os.path.dirname(sys.executable))