argv
What on Earth is it!?
Edit: If you can, will you please write a line or two and explain how it works?
If you have an executable python script and call it with arguments like this:
myscript.py -a -b --input myfile --another_argument
then sys.argv
is a list containing:
['myscript.py', '-a', '-b', '--input', 'myfile', '--another_argument']
Using it is the only way to access these arguments, and that is its main use. However, most applications use libraries such as the argparse module to access this information without needing to use sys.argv
directly.
It means arguments vector and it contains the arguments passed to the program. The first one is always the program name.
For example, if you executed your Python program like so...
$ python your_script.py --yes
...then your sys.argv
will contain your_script.py
and --yes
.
sys .argv will display the command line args passed when running a script or you can say sys.argv will store the command line arguments passed in python while running from terminal
It stores the arguments in a list ds.
sample usage: Create a file say: cmdlineargs.py and put the following in it:
import sys
print sys.argv
Now run the file in your terminal/cli :
python cmdlineargs.py
or something like
python cmdlineargs.py example example1
Notice what happens now. Your script will print everything passed in your cmd line argument while you ran that script.
Important to know:
print len(sys.argv) #total arguments passed
sys.argv[0] #this is your script name stored in sys.argv.
print sys.argv #display all arguments passed
sys.argv[0] #is the first argument passed, which is basically the filename.
sys.argv #stores all cmd line args in a list ds
You can look up each specific argument passed like this, probably:
cmdLineArg = len(sys.argv)
i=0
for argv in sys.argv:
if cmdLineArg<=len(sys.argv) :
print "argument",i,"is", str(sys.argv[i])
i=i+1
else:
print "Only script name in sys.argv"
Sample result:
Say you run the following in your terminal.
python cmdlineargs.py example example1
Your result should look something like:
argument 0 is cmdlineargs.py
argument 1 is example
argument 2 is example1
Notice argument 0 is the same as the file name . Hope this was helpful.
Thanks for the upvotes, improving my answer for the loop. A little more pythonian answer should look like this:
i=0
for argv in sys.argv:
if cmdLineArg==1:
print "Only script name in sys.argv"
elif (cmdLineArg>1 and cmdLineArg<=len(sys.argv)):
print "argument ",i,"is", str(argv)
i=i+1
print "total arguments passed:\t", totalargs
I too am new to python so I had a habit of declaring i and j for traversing arrays. :)
Try this simple program, name it as program.py
import sys
print sys.argv
and try executing
python program.py
python program.py a b c
python program.py hello world
Note what is argv now.
You can run python program with or without arguments. If you use arguments they are inside argv vector. For example
PYTHON PROGRAM!!!
#!/usr/bin/python
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
RUN SCRIPT LIKE THIS
$ python test.py arg1 arg2 arg3
AND RESULT IS
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
examples are from tutorialspoint
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:]))