我使用getopt从命令行获取选项。如何检查是否已设置选项。我试过将一个值设置为1并测试它并且它有效但我想知道是否还有另一种方法可以做到这一点?
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:])
答案 0 :(得分:4)
您事先将参数设置为None
,然后在解析后测试它们是否仍 None
:
inputfile = outputfile = degres = None
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 is None or degres is None:
print usage
sys.exit(1)
outputfile = outputfile or inputfile
rotate_picture(inputfile, outputfile, degres)
请注意,您在Python中使用and
和or
进行布尔测试,&
是按位 AND运算符;它将整数位组合成新的整数。
argparse版本将是:
import argparse
parser = argparse.ArgumentParser(description='Rotate an image')
parser.add_argument('inputfile', type=argparse.FileType('r+b'),
help='The file to rotate')
parser.add_argument('degrees', type=int,
help='The number of degrees to rotate')
parser.add_argument('-o', '--output', type=argparse.FileType('wb'),
help='The file to write the result to. Defaults to the inputfile')
args = parser.parse_args()
outputfile = args.output or args.inputfile
rotate_picture(args.inputfile, outputfile, args.degrees)
并自动为您生成帮助:
usage: [-h] [-o OUTPUT] inputfile degrees
Rotate an image
positional arguments:
inputfile The file to rotate
degrees The number of degrees to rotate
optional arguments:
-h, --help show this help message and exit
-o OUTPUT, --output OUTPUT
The file to write the result to. Defaults to the
inputfile