- 1 year ago
Is it possible to access the launching shortcut directory from a Python executalbe?
Yes, it's possible to access the directory from which a Python executable was launched. You can use the sys
module in Python to access the sys.argv
list, which contains command-line arguments passed to the script. The first item in this list is usually the path to the Python script or executable that was used to launch the script. You can use this information to determine the directory from which the script was launched.
Here's an example:
pythonimport os
import sys
def get_launching_directory():
script_path = sys.argv[0]
launching_directory = os.path.dirname(os.path.abspath(script_path))
return launching_directory
if __name__ == "__main__":
directory = get_launching_directory()
print("Launching directory:", directory)
When you run this script, it will print the directory from which the script was launched.
Please note that there are a couple of things to consider:
Command Line: If you're using a Python script, the launching directory would be the directory from which you executed the script in the command line.
Executable: If you've converted your Python script to a standalone executable (e.g., using tools like py2exe, pyinstaller, cx_Freeze, etc.), the launching directory would typically be the directory where the executable resides.
Symlinks: Be aware that symbolic links or shortcuts might affect the behavior. If you launch a script through a symlink or shortcut, the launching directory might be the directory of the symlink or shortcut, not the directory where the target of the symlink or shortcut is located.
In summary, you can use the sys.argv[0]
value to determine the path to the script or executable and then use os.path.dirname
to get the directory. Keep in mind the behavior can vary based on how the script or executable is launched.