I'm trying to use the argparse module to extract the arguments from it, but the naive implementation fails when called with the python interpreter:
1 import argparse
2 import sys
3
4 parser = argparse.ArgumentParser(description="some test program")
5 parser.add_argument('--some-option', action="store", dest="some_option")
6
7 parsed_args = parser.parse_args(sys.argv)
8 print(vars(parsed_args)
It fails because it detects the first argument as the name of the script - in this case "test.py":
~$: python3 ./test.py --some-option=5
usage: test.py [-h] [--some-option INPUT]
test.py: error: unrecognized arguments: ./test.py
The solution I have found at the moment is to search and remove the python scripts name from the arugments, but this seems like an unelegant hack, and will have issues if the first argument can legitimately be a python file:
1 import argparse
2 import sys
3
4 parser = argparse.ArgumentParser(description="some test program")
5 parser.add_argument('--some-option', action="store", dest="some_option")
6
7 print(sys.argv)
8 if sys.argv[0].find('.py') != -1:
9 args = sys.argv[1:]
10 else:
11 args = sys.argv
12
13 parsed_args = parser.parse_args(args)
14 print(vars(parsed_args)
Is there a better way to get rid of that pesky python file name when using argparse
Note: I cannot get rid of the call to the intepreter because this is part of a cross-platform build system, and thus has a makefile that sets the python executable to python3 or python3.exe depending on OS.