Search code examples
pythonpython-3.xpyinstaller

How to get the directory from which a Python executable is being called?


A Python 3 program has been compiled into an exe file called myapp.exe, and is located at a C:\path\to\myapp.exe or at /path/to/myapp.exe using pyinstaller.

Another program calls the executable from some other arbitrary location anywhere on the same machine. For example, from C:\another\arbitrary\path\ or from /another/arbitrary/path/.

What specific syntax must be added to the code that gets compiled into myapp.exe in order for myapp.exe to be able to programmatically refer to the other arbitrary path from which myapp.exe is being called at any given point in time?

Current Code

The current code for the myapp.py file that gets compiled into myapp.exe is:

print('Hello World!')

Desired Code

The code I am seeking should look something like:

yourCallingDirectoryAtAnotherArbitraryPath = code requested in this OP
print('Hello, you are calling from ', yourCallingDirectoryAtAnotherArbitraryPath)

This must work for any OS.


Solution

  • Usually the more difficult job is for the executable to find out where it is stored itself. When you start a program, the current directory is available to the executable with the shorthand pathname .

    So to get the absolute path of the current directory, it is as easy as:

    import os
    print (os.path.abspath("."))