Get the filename of the currently executing python script
Simple Shell
In a shell script it’s easy: dollar zero is the filename of the script, one is the first argument, two is the second and so on.
|
1 2 |
#!/bin/bash echo "Usage: $0 <arg1> [arg2]" |

Python Plurality
As you would expect, there are several ways to do this in a python script. Using stack from the inspect module will give you the full path and filename of how it was executed. If you run from a relative path such as ./src/file then the stack item will contain just that part.
|
1 2 3 |
#!/usr/bin/env python import inspect print inspect.stack()[0][1] |
And if you’re curious, executing this from python’s interactive shell instead of a python script yields this instead:
|
1 2 3 4 5 |
>>> import inspect >>> inspect.stack()[0][1] '<stdin>' >>> inspect.stack()[0] (<frame object at 0x1977480>, '<stdin>', 1, '<module>', None, None) |
I can imagine there are other ways to break this and end up with