MBasith MBasith - 1 year ago 77
Python Question

Python Arguments and Passing Floats in Arguments

I've run into a couple of issues using arguments within a python script. Can i please get some help or direction to get this code functional? Thank you in advance.

First issue: I am unable to specify multiple arguments at once.
For example I am able to pass a single argument fine:

$ ./ -a
$ ./ -c
$ ./ -d

However, I am looking for a way to pass multiple arguments in any position. Is there a way I can accomplish this?
For example, I would like the below to occur:

./ -a -c -d

# OR

./ -c -a

Second Issue: I am trying to pass both whole numbers and floats in the -b argument. But when I pass a float/decimal I get the below error. Is there a way I can pass both a float and whole number?

This works:

$ ./ -b 5
The number provided is: 5

But this does NOT:

$ ./ -b 5.50
Traceback (most recent call last):
File "./", line 18, in <module>
if int(sys.argv[2]) not in range(0,11):
ValueError: invalid literal for int() with base 10: '5.50'

Below is my testable code:

import sys

script_options = ['-a', '-b', '-c', '-d']
manual_flag = ''
build_flag = ''

if len(sys.argv) > 1:
if sys.argv[1] in script_options:
print('\n\t\tParameter "' + sys.argv[1] + '" is an invalid argument.\n')
if sys.argv[1] == '-a':
elif sys.argv[1] == '-b':
if int(sys.argv[2]) not in range(0,11):
print('Invalid interval. Please select a value bewteen 1-5s.')
print('The number provided is: ' + (sys.argv[2]))
elif sys.argv[1] == '-c':
manual_flag = 'Argument_C'
elif sys.argv[1] == '-d':
build_flag ='Argument_D'

Answer Source

You didn't actually provide the code you're using (aside from incidentally in the traceback),(Update: Code added later) but the answer is: Stop messing around with parsing sys.argv manually and use the argparse module (or docopt or something that doesn't involve rolling your own switch parsing).

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-a', action='store_true')
parser.add_argument('-b', metavar='INTERVAL', type=int, choices=range(11))
parser.add_argument('-c', action='store_true')
parser.add_argument('-d', action='store_true')
args = parser.parse_args()

if args.a: print('Argument_A')
if args.b is not None: print('The number provided is:', args.b)
if args.c: print('Argument_C')
if args.d: print('Argument_D')

If you want to accept int or float, the easiest solution is to just make type=float and use a consistent type (but the range check must be done outside the parsing step). If you must allow both, ast.literal_eval or a homegrown argparse type conversion function are options. Since you want a range check too (which range won't handle properly for float values that aren't equal to int values), roll a type checker:

def int_or_float(minval=None, maxval=None):
    def checker(val):
            val = int(val)
        except ValueError:
            val = float(val)
        if minval is not None and val < minval:
            raise argparse.ArgumentTypeError('%r must be >= %r' % (val, minval))
        if maxval is not None and val > maxval:
            raise argparse.ArgumentTypeError('%r must be <= %r' % (val, maxval))
        return val
    return checker

Then use it by replacing the definition for -b with:

# Might want int_or_float(0, 10) depending on range exclusivity rules
parser.add_argument('-b', metavar='INTERVAL', type=int_or_float(0, 11))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download