understanding sys.argv[]

Bengt Richter bokr at oz.net
Wed Aug 14 19:20:20 CEST 2002

On 14 Aug 2002 15:23:41 GMT, Don Low <mt at open2web.com> wrote:

>I'm learning Python with Core Python programming by W. Chun. In chpt 3
>there's a script which I more or less understand. Here's the original
>#!/usr/bin/env python
>"fgrepwc.py -- searches for string in text file"
>import sys
>import string
># print usage and exit
>def usage():
>    print "usage:  fgrepwc [ -i ] string file"
>    sys.exit(1)
># does all the work
>def filefind(word, filename):
>filefind(sys.argv[1], sys.argv[3]).  
>This works, although honestly I don't know why. Does the sys.argv[x] where x
>equals a number signify 1st arg, 2nd arg, etc, or what?  I don't get this.
The best way to learn about this kind of thing is to make a simple program
that will tell you what's happening. If you wonder about argv, just write
a program that will show you what's what, and run it, e.g., (you appear to be
on Linux) an example prog in prargv.py:

bokr at springbok:~/junk$ cat prargv.py
#!/usr/bin/env python
import sys
print sys.argv # print list as such
for i in range(len(sys.argv)):
    print 'argv[%s] = %s' % (i, sys.argv[i])

Then run it to see what it will do

bokr at springbok:~/junk$ ./prargv.py 1 2,3 "four" 'five 6'
['./prargv.py', '1', '2,3', 'four', 'five 6']
argv[0] = ./prargv.py
argv[1] = 1
argv[2] = 2,3
argv[3] = four
argv[4] = five 6

Note variations on argv[0] depending on how you start it:

bokr at springbok:~/junk$ ~/junk/prargv.py foo
['/home/bokr/junk/prargv.py', 'foo']
argv[0] = /home/bokr/junk/prargv.py
argv[1] = foo

bokr at springbok:~/junk$ python prargv.py bar
['prargv.py', 'bar']
argv[0] = prargv.py
argv[1] = bar

bokr at springbok:~/junk$ python ~/junk/prargv.py bar
['/home/bokr/junk/prargv.py', 'bar']
argv[0] = /home/bokr/junk/prargv.py
argv[1] = bar

Bengt Richter

More information about the Python-list mailing list