我是 Python 新手,我从 getopt 学到的是,我可以在执行 python 脚本时传递命令行参数。现在我的问题是,有没有办法不设置我可以在命令行中传递的参数数量?
我的代码看起来像这样:
try:
opts, args = getopt.getopt(sys.argv[1:],"h:1:2:3:4:",["help=", "1week=","2week=", "3week=", "4week="])
except getopt.GetoptError:
print 'test.py -1 <week 1> -2 <week 2> -3 <week 3> -4 <week 4>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -1 <week 1> -2 <week 2> -3 <week 3> -4 <week 4>'
sys.exit()
elif opt in ("-1", "--1week"):
week1 = arg
elif opt in ("-2", "--2week"):
week2 = arg
elif opt in ("-3", "--3week"):
week3 = arg
elif opt in ("-4", "--4week"):
week4 = arg
并运行我使用的上述代码
python test.py -1 89 -2 88 -3 87 -4 86
。无论如何我可以修改这个,因为我不必总是给出 4 个参数,但也有 3 个?我希望它灵活,有时我可能会给出 3 个或 4 个参数。