How does one acquire the directory of the Windows Shortcut calling a python script. I'd like to have multiple shortcuts in various places pointing to one script that I could edit if I wanted, but where the directory from which the script is called is accessible. Is this possible?
This script would likely then be compiled with py2exe or something, so if it is something that isn't possibly until THAT stage, I could go with that. Thanks!
Using os.getcwd() method is used for getting the Current Working Directory in Python. The absolute path to the current working directory is returned in a string by this function of the Python OS module.
The easiest solution is to just use a batch script instead of a shortcut.
All it needs is python C:\path\to\script\script.py
, and the script will have the correct CWD.
The default when creating a shortcut on windows is for the Start in:
property to be set to the folder the linked file resides in.
The script has no knowledge of the fact that it was called from a shortcut, let alone where that shortcut resides.
You can change the Start in:
property of the shortcut to the path of the folder the shortcut resides in.
Then you can use os.getcwd()
to get that path.
Unfortunately setting Start in:
to .
doesn't work.
In general you cannot obtain this information. You should use argv
to switch behaviour of your script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With