Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get python .exe path [duplicate]

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?

like image 963
Sobir Avatar asked Sep 11 '25 17:09

Sobir


1 Answers

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))
like image 136
wpercy Avatar answered Sep 13 '25 05:09

wpercy