optparse TypeError

D

dirknbr

I get an int object is not callable TypeError when I execute this. But
I don't understand why.

parser = optparse.OptionParser("usage: %lines [options] arg1")
parser.add_option("-l", "--lines", dest="lines",
default=10, type="int",
help="number of lines")
parser.add_option("-t", "--topbottom", dest="topbottom",
default="T", type="str",
help="T(op) or B(ottom)")

(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
lines=options.lines
tb=options.topbottom

Dirk
lines(args[0],topbottom=tb,maxi=lines)
 
S

Simon Brunning

I get an int object is not callable TypeError when I execute this. But
I don't understand why.
(snip)
   lines=options.lines

Here you are assigning the -l option to the name 'lines'.
   lines(args[0],topbottom=tb,maxi=lines)

Here you are attempting to call a function with the name 'lines'. But
'lines' has been assigned an integer above.

I'm assuming that elsewhere you've defined a function called 'lines'.
You'll need to call either the function or the option by another name.
 
M

Michele Simionato

I get an int object is not callable TypeError when I execute this. But
I don't understand why.

    parser = optparse.OptionParser("usage: %lines [options] arg1")
    parser.add_option("-l", "--lines", dest="lines",
                      default=10, type="int",
                      help="number of lines")
    parser.add_option("-t", "--topbottom", dest="topbottom",
                      default="T", type="str",
                      help="T(op) or B(ottom)")

    (options, args) = parser.parse_args()
    if len(args) != 1:
        parser.error("incorrect number of arguments")
    lines=options.lines
    tb=options.topbottom

Dirk
    lines(args[0],topbottom=tb,maxi=lines)

optparse is so old-fashioned. Use plac!

$ cat x.py
import plac

@plac.annotations(
lines=('number of lines', 'option', 'l', int),
topbottom=('T(op) or B(ottom)', 'option', 't', str, 'TB'))
def main(arg, lines=10, topbottom='T'):
print arg, lines, topbottom

if __name__ == '__main__':
plac.call(main)

$ python x.py -h
usage: x.py [-h] [-l 10] [-t T] arg

positional arguments:
arg

optional arguments:
-h, --help show this help message and exit
-l 10, --lines 10 number of lines
-t T, --topbottom T T(op) or B(ottom)


(see http://pypi.python.org/pypi/plac)
 
R

rantingrick

optparse is so old-fashioned. Use plac!

Hog wash! Both are archaic and asinine. Both clog your scripts with
wasted lines and your memory with complex interfaces far worse than
colon clogging junk food can hold a candle to. Give your *script* an
enema, and do *yourself* a favor by harnessing the simplistic elegance
of the "optphart" module instead!


#-- Start Script --#
def optphart(args):
d = {'args':[]}
for arg in args:
if arg.startswith('-'):
key, value = arg.split('=', 1)
options = value.split(',')
if len(options) > 1:
d[key[1:]] = options
else:
d[key[1:]] = [value]
else:
d['args'].append(arg)
return d


if __name__ == '__main__':
args = [
'nakedArgumentOne',
'nakedArgumentTwo',
'-file=aSingleFile.txt',
'-files=aFileOne.txt,aFileTwo.txt',
'-options=Op1,Op2,Op3,Op4',
'-help=this_is_some_unhelpful_help',
]
opts = optphart(args)
#print opts.keys()
for k,v in opts.items():
print '%s -> %s' %(k, v)
#-- End Script --#
 
M

Michele Simionato

The OP should be made aware that:

* plac is a third-party library with (TTBOMK) no prospect of inclusion
  in the standard library

* optparse is in the standard library and has been for many versions

* argparse is a third-party library that is now accepted for inclusion
  in the standard library, intended as a full optparse replacement
  <URL:http://www.python.org/dev/peps/pep-0389/>

All valid points. I will just add that plac is based on argparse and
nothing else, so it is an external dependency, yes, but not a large
dependency. Moreover the core is only 200 lines. People can just grab
http://micheles.googlecode.com/hg/plac/plac_core.py, and include it in
their personal code base, possibly adapting it (I mean for people
preferring recipes to external dependencies).

Michele Simionato
 
M

Michele Simionato

Give your *script* an
enema, and do *yourself* a favor by harnessing the simplistic elegance
of the "optphart" module instead!

#-- Start Script --#
def optphart(args):
    d = {'args':[]}
    for arg in args:
        if arg.startswith('-'):
            key, value = arg.split('=', 1)
            options = value.split(',')
            if len(options) > 1:
                d[key[1:]] = options
            else:
                d[key[1:]] = [value]
        else:
            d['args'].append(arg)
    return d

Probably I should not be answering this, but try to implement the
parsing required by the OP with this approach, including the
generation of the usage message and the error checking. Just try.

M. S.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top