Nototo Hoshi
Nototo Hoshi

Reputation: 11

Python location of script if run as .exe from different place on Windows

I have a python script:

C:\ProgramFiles\myscript.py

and have created and .exe version of it using pyinstaller:

C:\ProgramFiles\myscript.exe

Ive made sure that C:\ProgramFiles is in my environmental windows path, so that I can run the script from command prompt from any location.

Now, the thing is, I want the script to know what is its location. Ive tried some of the available solutions such as:

sys.argv[0]

or

os.path.abspath(__file__)

but these solutions only seem to be working while you are working with .py script and python path. Once I switch to .exe and using windows environmental path it doesn't work anymore. So when I run the program from some weird place, like:

C:\Users\John>myscript

it always assumes that the location where I ran the command from is the location where it is, none of the solutions will give me the result I want - which would be the original location:

C:\ProgramFiles\

Basically what Iam trying to achieve - I run a command prompt and run an .exe program in it (originally a .py script). Then windows searches its path variable to see if it can find the program someplace visible. And if the windows do find it, then it will be executed. And I want the program to be aware of where have the windows actually found it, not what is the current working directory.

Upvotes: 0

Views: 1174

Answers (2)

Nototo Hoshi
Nototo Hoshi

Reputation: 11

After some testing (thanks buran for his/her guidance), I ended up using this solution:

import sys
import os

if getattr(sys, 'frozen', False):
    script_location = sys.executable
else:
    script_location = os.path.abspath(__file__)
script_location = os.path.dirname(script_location) 

which currently seems to be working both for the .py version and the .exe version of the program build by pyinstaller.

The

sys._MEIPASS

was giving me location in

Appdata\Local\Temp 

which is not what I wanted.

Upvotes: 0

buran
buran

Reputation: 14233

You need to do the following in order to know the folder from which your script runs:

import sys, os
if getattr(sys, 'frozen', False):
    # we are running in a bundle
    bundle_dir = sys._MEIPASS
else:
    # we are running in a normal Python environment
    bundle_dir = os.path.dirname(os.path.abspath(__file__))

print(bundle_dir)

bundle_dir is the folder from which the script is executed. This way your code will work bot when as python script or after being converted to exe.

As I already mentioned in the comment, check Run-time Information section in PyInstaller docs.

Upvotes: 1

Related Questions