optparse with numpy.array?

Robert Kern robert.kern at gmail.com
Tue Jan 27 07:12:53 CET 2009


On 2009-01-27 00:01, Johan Ekh wrote:
> Thank you James,
> but I just can't optparse to accept an array, only integers, floats ans
> strings.
>
> My code looks like this
>
> from optparse import OptionParser
> parser = OptionParser()
> parser.add_option('-t', '--dt', action='store', type='float',
> dest='dt_i', default=0.1, help='time increment where lsoda saves results')
> parser.add_option('-T', '--tstop', action='store', type='float',
> dest='tstop_i', default=1.0, help='duration of the solution')
> parser.add_option('-m', '--mass_vector', action='store', type='float',
> dest='m_i', default=[1.0, 1.0], help='vector with lumped masses')
> op, args = parser.parse_args(sys.argv[1:])
>
> I want this to work for m_i = array([1.0, 2.0, 3.0]) but the optparse
> complains that m_i is not a float.

Well, yes, because you declared that --mass_vector was type='float'. You will 
need to subclass OptionParser in order to parse something that is not one of the 
included types. Yes, it is a bit cumbersome; it's one of the reasons I usually 
use the third-party argparse library instead. You only need to supply a parsing 
function rather than subclass.

I'm afraid I don't really understand what you want when you say that you want to 
create an array interactively. Can you show me an example command line that you 
want to parse? Keep in mind that in many shells, ()[] characters are specially 
handled by the shell and are not convenient for users.

BTW, I am subscribed to the list. You do not need to Cc me.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list