我使用getopt從命令行獲取選項。我如何檢查是否設置了選項。我試圖設置一個值爲1並測試它,它的工作原理,但我想知道是否有另一種方法來做到這一點?做一個測試python選項強制性的
def main(argv):
inputfile = ''
outputfile = ''
i = 0
o = 0
d = 0
usage = """
Usage: rotate.py [OPTIONS] ...
rotate.py -i img1.jpg -o img2.py -d 10
rotate.py -i img1.jpg -d 10
-h --help Display this usage message
-i --ifile <inputfile> The file to rotate
-o --ofile <outputfile> The file that will have the rotated image.
-d --degres <integer> The number of degres to rotate
"""
try:
opts, args = getopt.getopt(argv,"hi:o:d:",["ifile=","ofile=","degres=","help"])
except getopt.GetoptError:
print usage
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
print usage
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
i = 1
elif opt in ("-o", "--ofile"):
outputfile = arg
o = 1
elif opt in ("-d", "--degres"):
degres = arg
d = 1
if (inputfile in globals()) & (outputfile in globals()) & (degres in globals()):
rotate_picture(inputfile, outputfile, degres)
elif (inputfile in globals()) & (degres in globals()):
rotate_picture(inputfile, inputfile, degres)
else:
print usage
if __name__ == "__main__":
main(sys.argv[1:])
是爲時已晚指出,['argparse'(HTTP: //(從2.7開始的Python的一部分)支持解析強制參數並且更易於使用? –
來自'getopt'文檔:「對C++ getopt()函數不熟悉的用戶或者希望編寫更少代碼並獲得更好幫助和錯誤消息的用戶應該考慮使用argparse模塊,而不是*。」相信我,你會感謝你切換到'argparse'。 – SethMMorton
我已經經歷了argparse,你是對的,它更好:)。謝謝你的提示。 – user2040597