3

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?

Sobir
  • 125
  • 3
  • 9
  • 1
    have you tried `import sys; print sys.executable`? or `os.path.dirname(sys.argv[0])` – wpercy Feb 15 '19 at 20:47
  • Yeah, it's quite interesting to see what [`sys.executable`](https://docs.python.org/3/library/sys.html#sys.executable) is equal to for such a packaged Python script. If the full interpreter is packaged alongside, it may do the trick – ForceBru Feb 15 '19 at 20:51
  • @wpercy Thank you! I tried sys.executable and it works. It is the exact .exe path of my program. – Sobir Feb 15 '19 at 20:57
  • So when I write `os.chdir(sys.executable)` it will not work when run with python interpreter :). What suggestions now? – Sobir Feb 15 '19 at 21:00
  • `os.chdir(sys.executable)` is trying to change the current working directory to the executable file, **not** the folder it is in. – martineau Feb 15 '19 at 21:07
  • @SobirBobiev I've added an answer that should help – wpercy Feb 15 '19 at 21:24

1 Answers1

8

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))
wpercy
  • 9,636
  • 4
  • 33
  • 45