1

According to https://www.tutorialspoint.com/python/python_command_line_arguments.htm

first argument is always script name and it is also being counted in number of arguments.

which is sys.argv[0]

However, when I read other tutorial such as

https://www.cyberciti.biz/faq/python-command-line-arguments-argv-example/

it says that first argument is sys.argv[1]

#!/usr/bin/python
__author__ = 'nixCraft'
import sys total = len(sys.argv)
cmdargs = str(sys.argv)
print ("The total numbers of args passed to the script: %d " % total)
print ("Args list: %s " % cmdargs)
# Pharsing args one by one
print ("Script name: %s" % str(sys.argv[0]))
print ("First argument: %s" % str(sys.argv[1]))
print ("Second argument: %s" % str(sys.argv[2]))

Which one is correct and should be followed?

This is confusing especially to those who just started learning programming and Python.

  • could just run your code and find out.. – Derek Eden Feb 19 '20 at 00:28
  • I did, that why I put the sample code above. –  Feb 19 '20 at 00:29
  • 1
    The best way to think of it is that `sys.argv` is going to be a list of the things *after* the call to `python` in your shell, so, for example, `python myscript.py foo bar baz`, everything after python is `myscript.py foo bar baz` so `sys.argv == ['myscript.py', 'foo', 'bar', 'baz']` So, [here](https://docs.python.org/3/library/sys.html#sys.argv) are the docs which go into more detail – juanpa.arrivillaga Feb 19 '20 at 00:38

1 Answers1

0

sys.argv[0] is the name of the script. Technically it is the "first" argument, but is typically of no use to you, unless you don't know the name of the file you're executing. sys.argv[1], is the name of the first argument after the name of the script, so the first useful argument.

Gabe Spound
  • 568
  • 5
  • 28
  • 2
    Thanks @Gabe for helping me. It seems like Stack Overflow is getting unfriendly from day to day. Not everyone knows everything .. some people just started and simply just want the answer. –  Feb 19 '20 at 00:30