Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the directory of a Shortcut calling a Python Script

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!

like image 408
Cryptite Avatar asked Jul 05 '11 22:07

Cryptite


People also ask

How do I find out what directory a Python script is running from?

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.


2 Answers

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.

like image 141
Acorn Avatar answered Oct 11 '22 17:10

Acorn


In general you cannot obtain this information. You should use argv to switch behaviour of your script.

like image 21
David Heffernan Avatar answered Oct 11 '22 15:10

David Heffernan