Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why printing arguments in python doesn't work?

I'm trying to explain to my friend, how sys.argv works. And I ran this snippet from command line (tested on cmd and bash).

python -c "import sys; print(sys.argv)" bla stas

But to my surprise this is the output:

['-c', 'bla', 'stas']

And I'm stumped - why the expression in quotes "import sys; print(sys.argv)" is not part of the argument list? Shouldn't it be at the second place like this:

['-c', '"import sys; print(sys.argv)"', 'bla', 'stas']

?

like image 718
zbstof Avatar asked Jun 15 '26 10:06

zbstof


1 Answers

From the documentation:

argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'.

Putting the command itself in argv[] as well would be wrong, since it's not an argument to the script. The arguments are just bla and stas.

like image 162
Barmar Avatar answered Jun 16 '26 22:06

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!