【问题标题】:Python Main Function Command Line Argument Long ListPython 主函数命令行参数长列表
【发布时间】:2015-03-17 02:57:18
【问题描述】:

我正在尝试为 Caesars Shift 加密程序创建一个简单的 main 函数,但是我不太确定如何配置所有这些命令行 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"

提前致谢。

【问题讨论】:

    标签: command


    【解决方案1】:

    如果您还没有,您应该查看docopt。虽然我自己从未使用过它,但它非常受欢迎,应该非常适合您。

    【讨论】:

    • 好的,谢谢。我已经在 opt 上寻找了一些东西,但没有找到太多深入的报道。感谢您的回复。
    • 许多人发誓 docopt 而不是 Python 内置的任何东西。它看起来非常全面和可定制。
    猜你喜欢
    • 1970-01-01
    • 2020-04-28
    • 2012-10-04
    • 2015-08-20
    • 2013-05-30
    • 1970-01-01
    • 2017-09-09
    • 2012-02-20
    • 1970-01-01
    相关资源
    最近更新 更多