-2

What does the following chunk of code mean? I don't understand the concept of sys.argv. I heard it has something to do with command-line prompts but my vocabulary isn't good enough to understand that. Also the output is strange. I don't understand how a list is pulled up nor how the elements get in there or even where they come from and what they mean. This is really confusing me, so help understanding it would be much appreciated. Please use beinner terms so I can understand it.

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
HAMZAH AHMED
  • 159
  • 5

2 Answers2

4

Most programs accept arguments to change how they behave. e.g.

grep some_string myfile.ext

This command (on unix systems) looks for 'some_string' in myfile.ext and prints matching lines to the console.

So the question is how does grep (the program that is being run), know what to look for, or what file to look in? The answer is obvious -- It gets passed those arguments via the command line. You have the power to pass arguments from the commandlint to your python programs too:

python my_python_file.py argument1 argument2

In this case, if my_python_file.py had the contents in your question, sys.argv would contain ['my_python_file.py', 'argument1', 'argument2']

And so you can look in sys.argv and see 'argument1' in there and have your code take certain actions accordingly. Note that it is fairly uncommon to parse sys.argv by hand unless it is a really simple case. Normally, you would use something like argparse to parse the arguments for you and give you back the parsed information in a much more easy to manage format.

mgilson
  • 300,191
  • 65
  • 633
  • 696
2

sys.argv is a list of strings containing the arguments when the Python script was executed (i.e. >> python main.py arg1 arg2).

Note that the first argument will always be the name of the command. The first "actual" argument is located in sys.argv[1] (assuming at least one argument was passed in).

Matthias
  • 4,481
  • 12
  • 45
  • 84
Russley Shaw
  • 441
  • 2
  • 9