Python Argparse: Issue with optional arguments which are negative numbers

Ger picture Ger · Jan 26, 2012 · Viewed 13.6k times · Source

I'm having a small issue with argparse. I have an option xlim which is the xrange of a plot. I want to be able to pass numbers like -2e-5. However this does not work - argparse interprets this is a positional argument. If I do -0.00002 it works: argparse reads it as a negative number. Is it possible to have able to read in -2e-3?

The code is below, and an example of how I would run it is:

./blaa.py --xlim -2.e-3 1e4 

If I do the following it works:

./blaa.py --xlim -0.002 1e4 

The code:

parser.add_argument('--xlim', nargs = 2,
                  help = 'X axis limits',
                  action = 'store', type = float, 
                  default = [-1.e-3, 1.e-3])

Whilst I can get it to work this way I would really rather be able to use scientific notation. Anyone have any ideas?

Cheers

Answer

itub picture itub · Jun 21, 2013

One workaround I've found is to quote the value, but adding a space. That is,

./blaa.py --xlim " -2.e-3" 1e4

This way argparse won't think -2.e-3 is an option name because the first character is not a hyphen-dash, but it will still be converted properly to a float because float(string) ignores spaces on the left.