I'm just curious about the sys.argv
behavior I find strange and inconsistent.
I expected sys.argv
to only contain the script arguments (not the arguments that are parsed by the python3
executable).
In practice, I see that sys.argv
contains the -c
argument intended for python3
. What surprises me then is that the next argument - the script body - is missing. I expect either 2 arguments or 4, but not 3.
What's the logic behind this?
$ python3 -c 'import sys;print(sys.argv)' 1 2
['-c', '1', '2']
Update:
Ok. I got it. This only happens with the -c
argument and not other arguments:
$ python3 -b -c 'import sys;print(sys.argv)' -d 1 2
['-c', '-d', '1', '2']
I still find it confusing and with that in the inline script case the argv[0]
would contain the script text or -c <script text>
or python3 -c <script text>
P.S. Here is the script that initially confused me:
python3 -c '
import argparse
import sys
parser = argparse.ArgumentParser()
print(parser.parse_known_args(sys.argv))
' -a 1 -b 2 -c 3
(Namespace(), ['-c', '-a', '1', '-b', '2', '-c', '3'])
I was surprised to see the first -c in the output. Turns out you should not just pass argv
to parse_known_args
.