所以我写了一个程序,我想给它传递一个文件名和一个整数,或者只是一个整数。确定哪个参数是整数的最佳方法是什么?这就是我所拥有的:
import sys
if len(sys.argv) > 1):
for e in sys.argv:
try:
bio = map(e, int)
except:
pass
提前致谢
所以我写了一个程序,我想给它传递一个文件名和一个整数,或者只是一个整数。确定哪个参数是整数的最佳方法是什么?这就是我所拥有的:
import sys
if len(sys.argv) > 1):
for e in sys.argv:
try:
bio = map(e, int)
except:
pass
提前致谢
isdigit()
您可以使用 string方法检查参数是否为整数:
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
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)
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")