argv
What on Earth is it!?
Edit: If you can, will you please write a line or two and explain how it works?
Before you waste time "starting to learn some higher levels of code", you need to learn how to find information like this. Knowing how to look up an unfamiliar function/class/variable, without having to wait 30-60 minutes for people on SO to answer you (and apparently rack up multiple downvotes in the process), will come in far more useful than adding one more piece of information to your repertoire.
From the built-in help:
>>> import sys
>>> help(sys)
…
argv -- command line arguments; argv[0] is the script pathname if known
…
This works with any module. Often, individual classes and functions within the modules have more detailed information (but that doesn't work for argv, since it's just a list
, and lists don't have custom help).
If that's not enough information, the documentation (or the 2.x documentation) says:
sys.argv
The list of command line arguments passed to a Python script. 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'. If no script name was passed to the Python interpreter, argv[0] is the empty string.
To loop over the standard input, or the list of files given on the command line, see the fileinput module.
The first web result for googling "python argv" is a blog post by Python author Guido that may be a bit too advanced for you, but the second one is a tutorial on "Command Line Arguments".
As most of these things tell you, many simple scripts can often just use fileinput
instead of dealing with argv
directly, while more complicated scripts often need to use argparse
(or optparse
, getopt
, or other alternatives, if you need to work with Python 2.6 or earlier).
One example where sys.argv
is just right is this trivial program to convert relative pathnames to absolute (for those who aren't on linux or other platforms that come with an abspath, GNU readlink, or similar tool built-in):
import os, sys
print('\n'.join(os.path.abspath(arg) for arg in sys.argv[1:]))
Or this "add" tool that just adds a bunch of numbers (for those stuck with cmd.exe or other defective shells that don't have arithmetic built in):
import sys
print(sum(int(arg) for arg in sys.argv[1:]))