0

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.

starfry
  • 9,273
  • 7
  • 66
  • 96
  • See the answer here: http://stackoverflow.com/questions/570183/can-i-use-perls-switches-with-bin-env-in-the-shebang-line – Armin Rigo Feb 03 '13 at 18:08
  • That doesn't really answer my question. It does confirm my understanding of how the command on the shebang line is presented in argv but it doesn't explain how a Python script should detect that it has been involed via a shebang. – starfry Feb 03 '13 at 20:09
  • I haven't been able to find a better solution to the one I presented in my question. It works fine for me but I haven't suggested it as an answer because I still hope for something better to come along. – starfry Mar 01 '13 at 10:37

0 Answers0