[Tutor] Help with ARGV parsing
Hans Nowak
ivnowa@hvision.nl
Mon, 31 May 1999 22:19:04 +0200
On 31 May 99, Jerry Alexandratos wrote:
> I'm new to Python. But I really like what I see so far. I'm looking to
> write and rewrite some scripts. I'm having some trouble trying to
> figure out how to parse command-line arguments under Python.
>
> Can anyone provide me with some pointers?
The most straightforward way is to look at sys.argv, a list which
contains the command line arguments.
Try this very tiny program:
---begin--->8------
import sys
print sys.argv[1:]
---end----->8------
Now call this little script on the command line with various
arguments, and see what happens.
showargs.py 1 2 3
just yields ['1', '2', '3'], but
showargs.py 1 "hello world" 2
yields ['1', 'hello world', '2']
Some more experimenting won't hurt. :o) Note that each element of
sys.argv is a string. Also note that I used a slice, sys.argv[1:].
The 0th argument of the list is the name of the calling program.
If you need more sophisticated parsing, you can take a look at the
getopt module. You can specify switches and such. I think there are
also a few third party modules around which also deal with parsing of
the command line.
Veel liefs,
--Hans Nowak (ivnowa@hvision.nl)
Homepage: http://fly.to/zephyrfalcon