1

I have a script which needs to be able to save its own full path into a variable. So far I have tried:

sys.argv[0]
os.path.realpath(__file__)
os.path.abspath(__file__)

these all work with the regular python script I have. However once I convert it to an executable with pyinstaller, the above methods no longer work for getting the path of the .exe. They either detect the .exe as a .py or simply don't detect it at all. Why is this so and what method can I use that will always get the name of the script whether it is a .py or .exe. Is there a function that can get the full path of the file whether it is a normal .py file or a python .exe file. I'm on python 2.7 using windows 10

3 Answers 3

2

This may do the trick but if you find a better solution dont esitate to drop this.

import subprocess

path = subprocess.Popen('cd')
Sign up to request clarification or add additional context in comments.

Comments

1

This works on Py 3.4 / Win 10.

from win32api import GetCommandLine, GetFullPathName

print (GetCommandLine())

print (GetFullPathName('temp.exe'))

Output:

Microsoft Windows [Version 10.0.15063]
(c) 2017 Microsoft Corporation. All rights reserved.

C:\scratch\dist\temp>temp
temp
C:\scratch\dist\temp\temp.exe

C:\scratch\dist\temp>

I displayed the command line because you might have to perform additional steps to isolate the script's file name for use in GetFullPathName.

Edit: I made a correction! Since I knew the name of the script (temp.py) I knew the name that pyinstaller would assign to the executable (temp.exe), and I could use GetFullPathName against it.

Comments

1

This works for all file extensions .py, .exe and even if the .exe is changed to .scr the program still works:

import sys
import os
print os.path.abspath(sys.argv[0])

Command line output :

C:\Users\angus\Desktop>t.py
C:\Users\angus\Desktop\t.py

C:\Users\angus\Desktop\dist\t>t.exe
C:\Users\angus\Desktop\dist\t\t.exe

C:\Users\angus\Desktop\dist\t>t.scr
C:\Users\angus\Desktop\dist\t\t.scr

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.