[Tutor] sending both a filename and an argument from the command line

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Nov 23 17:04:16 EST 2003

On Sun, 23 Nov 2003, Ben Vinger wrote:

> OK, thanks to that advice, it works, but behaves strangely.  (it prints
> the correct output, but also some comments and code to the console)

> parser.add_option("--ip", dest="ip address to test",
>                   help="example: python ip.py capture.txt --ip")

Hi Ben,

The 'dest' doesn't stand for "description", but "destination".  We use it
to tell Python what to name to use when it is storing the option.  Try:

                      help="example: python ip.py capture.txt --ip")

Take a look again at:


if you feel shaky on any of the parameters that add_option() can take.

> options, argv = parser.parse_args(sys.argv)
> for line in  fileinput.input(argv):
>     if line.find(sys.argv[3]) > 0:
>         print line

The point of using optparse is to avoid having to touch sys.argv[3], for
how do we know that the fourth parameter is the ip address parameter?
What if the user does something like this:

    python ip.py --ip capture.txt

Once we parse our arguments using parse_args(), we can say something like:


and that should get us the IP address.  Take advantage of the work that
optparse is doing for you.  *grin*

> The output of
> python ip.py capture.txt --ip
> looks like this (note the unwanted lines from the script):

Ah!  Go back and edit the line:

> for line in  fileinput.input(argv):

'argv' probably still contains the name of the 'ip.py' script at the very
beginning!  So you'll probably want to slice argv[0] out.  Something like:

    for line in fileinput.input(argv[1:]):

should keep it from including itself as part of the input stream.

Hope this helps!

More information about the Tutor mailing list