I have simple script interpreter written in Python that processes a script written in a text file. I can refer to the interpreter using a shebang at the top of the script so that I can then execute the script directly.
The interpreter has some logic to detect when it is invoked via the shebang so that it can adjust the argument list to compensate. This is necessary because, when called directly, each argument is a separate item in argv but, when called via the shebang, all arguments on the shebang line are contained in the first argument string and the name of the script is in the second argument string with any arguments given directly to the script following thereafter.
The way I check for the shebang is as follows:
def main(name, argv):
...
if len(argv) >= 2 and name[0] == '/' and os.path.isfile(argv[1]) and os.access(argv[1], os.X_OK):
input = open(argv[1])
arglist = argv[0].split() + argv[2:]
else:
arglist = argv
input = sys.stdin
...
sys.exit(main(sys.argv[0], sys.argv[1:]))
What this does is assume execution was via shebang if there is at least 2 argv values, the command name begins with a "/" (the shebang executable path is absolute) and the script name in argv[1] is an executable file. If execution is via a shebang then the argument list is argv[0] split out plus argv[2] onwards appended to that list.
I would like to know whether this is correct or if there is another way to more definately determine this. What I have done works fine for all the scenarios that I need to use but I would be interested to learn of a better way if there is one.