Python: Test if an argument is an integer
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.
str.isdigit()
can be used to test if a string is comprised solely of numbers.
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))
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))
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:]
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."
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
>>> 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.
You can cast the argument and try... except the ValueError.
If you are using sys.argv, also investigate argparse.
精彩评论