command line arguments (newbie...)

Matteo Risoldi Matteo.Risoldi at cern.ch
Tue Nov 25 08:47:08 EST 2003


Hello,

I could not find the answer to the following through a search, so I thought
I could ask here. Thanks to everyone who would try and give a suggestion.
In this program I did, I am parsgin command line arguments through the
getopt.getopt function in the following way (note: try/except and other
non-relevant stuff has been omitted for clarity). Note that thr "argv"
parameter of main is actually sys.argv[1:].

def main(argv):
        opts, args=getopt.getopt(argv, "f:q:d:vro:t:h",
["file=","query=","database=","verbose","reformat","outfile=","tabulate=","h
elp"])
        ....
        ....
        for opt, arg in opts:
            if opt in ("-t","--tabulate"):
                separator=arg


This lets me assign the parameter of the "-t" argument to the "separator"
variable.
Still, I would like to be able to use the "-t" argument with OR without a
parameter, i.e. if I specify something after -t, it should go into
"separator", but if I don't specify anything, "separator" should keep its
default value (which is set elsewhere).
Now, the problem is that with getopt.getopt, if I put "t:"in the option
list, then I HAVE to put something after it; if I put only a "-t" on the
command line, I get a getopt.GetoptError exception. I have tried putting
both "t:" and "t" in the option list, but this won't work. At first I had
thought about testing "if arg" and only then assigning a value to separator,
but as I said the "-t" argument without parameters would not even be
accepted.

Any suggestion on how to achieve this?

Thank you very much.

Cheers.
Matteo






More information about the Python-list mailing list