我正在尝试为Caesars Shift加密程序制作一个简单的主函数,但是我不太确定如何配置所有这些命令行opt/arg的东西。 我想将程序配置为接受命令行参数,如下所示:
./caesars.py -e 13 message to encrypt
13 是班次的数量,以下行是要加密的消息。 我已经定义了函数,但我只是不确定如何将 opt arg 的东西配置为接受 argv[1] 之后的第一个参数作为键,然后所有内容都拆分为列表/长字符串。 这是我到目前为止所拥有的:
def main():
global decoder
global encoder
if not len(sys.argv[1:]):
usage()
# read the commandline options
try:
opts, args = getopt.getopt(sys.argv[1:],"hd:e:", ¬
["help","decode","encode"])
except getopt.GetoptError as err:
print str(err)
usage()
for o,a in opts:
if o in ("-h","--help"):
usage()
elif o in ("-d","--decode"):
decode = True
elif o in ("-e", "--encode"):
encode = True
else:
assert False,"Unhandled Option"
提前谢谢。
如果你还没有,你应该看看docopt。虽然我自己从未使用过它,但它非常受欢迎,应该非常适合您。