Is there a way in a Python script to determine if the caller provided the interpreter on the command line or if the shebang line was used to determine the interpreter to use?

As a simple example, myscript.py (which has executable permissions):

#!/bin/env python
import sys
print sys.argv

I want to know if this script was called like:

$ python myscript.py


$ ./myscript.py

sys.argv[0] is just "myscript.py" in either case.

  • Would it be an option to change the shebang line? Apr 27, 2020 at 22:00
  • Yes, I can change the shebang line as necessary.
    – C Smith
    Apr 29, 2020 at 10:49

1 Answer 1


This can be achieved by using an environment variable which is (indirectly) set via the shebang line.

In theory the same variable could be set in the shell but unless someone tries to explicitly fool the detection mechanism this should be fine.

Unfortunately the shebang line is limited to two arguments which is not enough (at least I am not aware of such a solution). Thus you need a helper script. Luckily the Linux kernel does not require the shebang interpreter to be a binary:


#! /bin/bash
via_shebang=1 bash "$1"

Then you use that script as shebang interpreter:

#! /usr/local/bin/shebang-bash.sh

In the script you just check the value / existence of $via_shebang.

  • Works for me. Thanks!
    – C Smith
    May 5, 2020 at 15:58
  • Note: I did change the "$1" to "$@" in order to get additional command line arguments. And since my use case is python, I have shebang-python.sh: #! /bin/bash via_shebang=1 python "$@"
    – C Smith
    May 5, 2020 at 16:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .