从python命令行参数中过滤整数

时间:2012-07-19 18:59:46

标签: python

所以我写了一个程序,我想传递一个文件名和一个整数或只是一个整数。什么是确定哪个参数是整数的最佳方法?这就是我所拥有的:

import sys

if len(sys.argv) > 1):
    for e in sys.argv:
        try:
            bio = map(e, int)
        except:
            pass

提前致谢

3 个答案:

答案 0 :(得分:8)

您可以检查参数是否是带字符串isdigit()方法的整数:

import sys

if len(sys.argv) > 1:
    for e in sys.argv:
        if e.isdigit():
            # all characters in e are digits and there is at least one character in e
        else:
            # it is possibly your filename argument

但是,我应该鼓励你给argparse库提供机会:http://docs.python.org/dev/library/argparse.html

import argparse
parser = argparse.ArgumentParser(description = 'A simple description')

parser.add_argument('-f', action = 'store', dest =  'filename', required = False)
parser.add_argument('-n', action = 'store', dest = 'n', required = True, type=int)

arguments = parser.parse_args()

print arguments.n
print arguments.filename

答案 1 :(得分:2)

def isint(val):
    try:
       int(val)
       return True
    except:
       return False

int_args = filter(isint,sys.argv)
not_int_args = set(sys.argv) - set(int_args)

答案 2 :(得分:1)

if len(sys.argv) == 1: #user passed in only one argument. It must be an integer.
    bio = int(sys.argv[0])
elif len(sys.argv) == 2: #user passed in two arguments: filename and integer.
    filename = sys.argv[0]
    bio = int(sys.argv[1])
else: #user didn't pass in the right number of arguments
    raise Exception("Expected one or two arguments")