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 from /tmp
file is baz.py
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 from /tmp
file is baz.py
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.
Aside from the aforementioned sys.argv[0], it is also possible to use the __main__:
import __main__
print(__main__.__file__)
Beware, however, this is only useful in very rare circumstances;
and it always creates an import loop, meaning that the __main__ will not be fully executed at that moment.