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.

magnifying glass searchSo how do you perform this operation in python?

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.

And if you’re curious, executing this from python’s interactive shell instead of a python script yields this instead:

I can imagine there are other ways to break this and end up with or a pipe or something weird instead, but for most cases, this should work just fine.


Posted on July 5th, by admica in howto, python.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">