What is sys.argv?sys.argv is the list of commandline arguments passed to the Python program. argv represents all the items that come along via the commandline input, it's basically a an array holding the command line arguments of our program. Don't forget that the counting starts at zero (0) not one (1).
How do I use it?To use it, you will first have to import it (import sys) The first argument, sys.argv, is always the name of the program as it was invoked, and sys.argv is the first argument you pass to the program. It's common that you slice the list to access the actual command line argument:
import sys program_name = sys.argv arguments = sys.argv[1:] count = len(arguments)
This is an example on how to read the argument from the command line
import sys for x in sys.argv: print "Argument: ", x
len(sys.argv) , checks how many arguments that have been entered. len(sys.argv) != 2 just checks whether you entered at least two elements
import sys if len (sys.argv) != 2 : print "Usage: python ex.py " sys.exit (1)
To run it, simple type: >python ex.py Argument: ex.py >python ex.py hello Argument: ex.py Argument: hello >python ex.py hello world Argument: ex.py Argument: hello Argument: world
Recommended Python Training – DataCamp
For Python training, our top recommendation is DataCamp.
Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.
Datacamp has beginner to advanced Python training that programmers of all levels benefit from.
Read more about: