Question

I have a python script which acts as launcher for other scripts. The script launches scripts from input arguments, following is some relevant code:

try:
    if verbose:
       print("Calling script ", args.script, " with arguments", *args.script_argument)
    os.execl(args.script, *args.script_argument)
except OSError as e:
    print("OSError: [Errno {0}] {1}: {2}".format(e.errno, e.strerror, args.script), file=sys.stderr)

args is an object returned by parse_args() from ArgumentParser. args.script_arguments is retrieved with nargs=argparse.REMAINDER.

This is the script the launcher is calling:

import sys

if __name__ == '__main__':
    print(sys.argv)

From the print before the os.execl call, I can see that the argument is properly set, however the script prints an argument less.

For example, if call the launcher with ./launcher.py -v script foo bar

The launcher will print, Calling script script with arguments foo bar.

However, the script prints ['script.py', 'bar']. Why isn't foo printed from the script?

Was it helpful?

Solution

The first argument you pass to os.execl (after the script argument) is the "name" of the program being run (it can be anything, doesn't have to be the actual path to the executable file). That's what script.py would see as its sys.argv[0] (see the docs, and also this question, for example, explaining how argv[0] works).

From the docs:

argv[0] is the script name (it is operating system dependent whether this is a full pathname or not)

To get the behavior you expect, call it like:

os.execl(args.script, args.script, *args.script_argument)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top