How can I find the full path to the currently running Python script? That is to say, what do I have to do to achieve this:
$ pwd
/tmp
$ python baz.py
running
The directory of the script which python is executing is added to sys.path
This is actually an array (list) which contains other paths.
The first element contains the full path where the script is located (for windows).
Therefore, for windows, one can use:
import sys
path = sys.path[0]
print(path)
Others have suggested using sys.argv[0]
which works in a very similar way and is complete.
import sys
path = os.path.dirname(sys.argv[0])
print(path)
Note that sys.argv[0]
contains the full working directory (path) + filename whereas sys.path[0]
is the current working directory without the filename.
I have tested sys.path[0]
on windows and it works. I have not tested on other operating systems outside of windows, so somebody may wish to comment on this.