help with comparison

Tim Roberts timr at probo.com
Thu Nov 20 01:26:54 EST 2008


tekion <tekion at gmail.com> wrote:
>
>Could some one take a look at the below code snipet which keep
>failing:
>
>import optparse
>p = optparse.OptionParser(description="script to do stuff",
>prog="myscript.py", ....)
>p.add_option("-c" "--compress", help="0 is noncompress")
>function1(options.compress)
>
>here's what the what function definition looks like:
>function1(zipfile) :
>if (zipfile == 1):
>   do stuff here with for compress file
>else
>   do stuff here
>
>when I call the script "myscript.py 1", the above test keeps falling
>to the else clause.  I am thinking the object zipfile is not the same
>as "1". Any thoughts as how I should test if the argument being pass
>in and parse by optparse is 1 or "0"?  Thanks.

There are many problems with this.  This is NOT your real code.  You're not
showing us the call to parse_args, so we can't see where the "options"
variable comes from, and the declaration of function1 is wrong.  When
asking a question like this, you should always include runnable code, to
make it easier for us to reproduce the problem.

However, I will assume that you have this:
    options, args = p.parse_args()

Did you even TRY printing out "options" and "args" to make sure that they
contained what you expected?  If you had run even one or two experiments,
two things would become clear.

1. When you call "myscript.py 1", you are not providing a value for the
"-c" parameter.  The "1" goes into "args", and options.compress will ALWAYS
be None.  You would need to say "myscript.py -c 1"

2. Options are strings.  It's simple character manipulation.  So,
options.compress will NEVER be 1.  If you did "myscript.py -c 1", then
options.compress will be "1".  That's a string, not a number.

If what you really want is "present" vs "not present", then use this:

    function1( options.compress )

    def function1( zipfile=None ):
        if zipfile:
            # compress
        else:
            # do not compress

However, that will read "0" as true.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list