16

I want to write a python script that takes 3 parameters. The first parameter is a string, the second is an integer, and the third is also an integer.

I want to put conditional checks at the start to ensure that the proper number of arguments are provided, and they are the right type before proceeding.

I know we can use sys.argv to get the argument list, but I don't know how to test that a parameter is an integer before assigning it to my local variable for use.

Any help would be greatly appreciated.

1
  • 1
    What version of Python are you running? Commented Nov 19, 2010 at 19:45

8 Answers 8

22

str.isdigit() can be used to test if a string is comprised solely of numbers.

Sign up to request clarification or add additional context in comments.

Comments

11

More generally, you can use isinstance to see if something is an instance of a class.

Obviously, in the case of script arguments, everything is a string, but if you are receiving arguments to a function/method and want to check them, you can use:

def foo(bar):
    if not isinstance(bar, int):
        bar = int(bar)
    # continue processing...

You can also pass a tuple of classes to isinstance:

isinstance(bar, (int, float, decimal.Decimal))

1 Comment

not applicable to this case, all cmd-line arguments are received as strings. but i did not know that one can pass tupples to isinstance, so thanks - i learnt.
10

If you're running Python 2.7, try importing argparse. Python 3.2 will also use it, and it is the new preferred way to parse arguments.

This sample code from the Python documentation page takes in a list of ints and finds either the max or the sum of the numbers passed.

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

Comments

6

Python way is to try and fail if the input does not support operation like

try:
   sys.argv = sys.argv[:1]+map(int,sys.argv[1:])
except:
   print 'Incorrect integers', sys.argv[1:]

2 Comments

I used this construct (except TypeError) but it didn't catch as a TypeError for value 1x. I got ValueError: invalid literal for int() with base 10: '1x'. So I will respectfully edit the answer to make the except generic.
Except for the print parentheses that should be included for python 3.4+, can the above try block be used as is for python 3.4+ ??? ---- I get an error, that says I cannot concatenate map to list. As a result the test always jump to the exception clause. Cheers,
4

You can use type to determine the type of any object in Python. This works in Python 2.6, I don't personally know if it's present in other versions.

obvious_string = "This is a string."
if type(obvious_string) != int:
    print "Bro, that is so _not_ an integer."
else:
    print "Thanks for the integer, brotato chip."

1 Comment

The problem with this is that all arguments passed through sys.argv are by definition strings -- what the poster needs to know is 'can I convert this argument to an int or not?' If not using argparse, the best way is (as noted elsewhere) to try the conversion inside a try/except block.
4

I am new to Python so I am posting this not only to help but also be helped: get comments on why my approach is/isn't the the best one, that is.

So, with the disclaimer that I am not an experienced python dev, here is what I would do:

inp = sys.argv[x]
try:
    input = int(inp)
except ValueError:
    print("Input is not an integer")

What the above does is that it puts sys.argv[x] to inp and then tries to put the integer form of inp to input. If there is not an integer form of inp then inp is not a number so a ValueError exception is raised.

I take it that's your main problem and you know how to check if you have all three parameters in the correct form. If not, just let us know and I am sure you will get more answers. :)

Just realized Tony Veijalainen posted a similar answer

Comments

1
>>> int('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'

Give it to int. If it doesn't raise a ValueError then the string was an integer.

Comments

0

You can cast the argument and try... except the ValueError.

If you are using sys.argv, also investigate argparse.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.