First, you need to make a slight difference. The argparse
module argparse
not parse command line arguments like the shell does. The shell is responsible for converting the string you enter into the shell into tokens, which are then passed to sys.argv
, python array / sequence of command line arguments. The argparse
module just makes sense that appears in sys.argv
.
This difference will clarify both of the “mistakes” you have noticed. First, consider -w "-4.5.5-double_non-parallel_gcc"
(note the lack of an equal sign). The shell parses these two tokens as -w
and -4.5.5-double_non-parallel_gcc
, and both of these lines are passed to sys.argv. Without an equal sign, it looks like two parameters: -w
(without an argument) and -4
with .5.5-double_non-parallel_gcc
as an argument. You need an equal sign so that everything is parsed as a single token.
DEVELOPED SECTION
As for 2&>
, for argparse it is impossible to control whether a given token is considered as an argument or not. If something appears in sys.argv, it means that your shell considers it as an argument.
The pilot icon is an error message. Note that the message is not unrecognized arguments: 2&>
, but rather unrecognized arguments: 2
. Your shell recognizes "&>" as output redirection and accordingly analyzes the rest of the line (including the log file). The only argument that is passed is "2" because 2&>
not a real type of redirect. ( &>
already covers both stderr and stdout, so what would add 2
?)
In a comment, you argued that optparse
could "handle" 2 &> ". This is actually not the case. The optparse
module did exactly what argparse
does, but optparse
does not check for positional arguments such as argparse
. In fact, optparse
makes a real programming error (in this case, using 2&>
as a type of shell redirection), gliding over undetected! You should post your original optparse code, but I suspect you have analyzed your arguments as follows:
opt, args = parser.parse_args()
Your script does not accept positional arguments, so I think you haven’t done anything else with args
. But if you checked args
, you will find that 2
was considered a positional argument!
In general, if the script does not accept positional arguments, and you use optparse
, a good check is that you are not receiving positional arguments, for example:
opt, args = parser.parse_args() if args: parser.error("script takes no positional arguments")
The argparse
module does this for you, which makes it miles ahead of optparse
(among other reasons).