【问题标题】:Getopt multiple argument syntaxesGetopt 多参数语法
【发布时间】:2016-10-02 14:25:48
【问题描述】:

所以我正在学习我正在学习的 Python 课程中的一项作业,但遇到了一些我无法真正找到更多信息的事情(无论是在 SO、Google 还是在课件中)。

我需要有关如何处理具有多种语法类型的参数的帮助 - 例如 [arg] 和 ,这是我无法找到任何进一步信息的内容。 p>

这是一个应该可以工作的示例用例。

>>> ./marvin-cli.py --output=<filename.txt> ping <http://google.com>
>>> Syntax error near unexpected token 'newline'

以下代码适用于我没有定义任何进一步输出而不是写入控制台的任何用例:

# Switch through all options
try:

    opts, args = getopt.getopt(sys.argv[1:], "hsv", ["help","version","silent", "get=", "ping=", "verbose", "input=", "json"])
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            printUsage(EXIT_SUCCESS)
        elif opt in ("-s", "--silent"):
            VERBOSE = False 
        elif opt in ("--verbose"):
            VERBOSE = True 
        elif opt in ("--ping"):
            ping(arg)
        elif opt in ("--input"):
            print("Printing to: ", arg)
        else:
            assert False, "Unhandled option"


except Exception as err:
    print("Error " ,err)
    print(MSG_USAGE)
    # Prints the callstack, good for debugging, comment out for production
    #traceback.print_exception(Exception, err, None)
    sys.exit(EXIT_USAGE)
#print(sys.argv[1])

示例用法:

>>> ./marvin-cli.py ping http://google.com
>>> Latency 100ms

这是一个显示 ping 工作原理的 sn-p:

def ping(URL):
    #Getting necessary imports
    import requests
    import time

    #Setting up variables
    start = time.time()
    req = requests.head(URL)
    end = time.time()

    #printing result
    if VERBOSE == False:
        print("I'm pinging: ", URL)
        print("Received HTTP response (status code): ", req.status_code)

    print("Latency: {}ms".format(round((end - start) * 1000, 2)))

【问题讨论】:

  • 您的问题到底是什么?是否要将 --output 添加到您的 getopt 解析中?
  • 我认为这个问题很明显......我需要处理多个参数语法,其中参数应该同时在 / [] 或
  • 您需要使用getopt吗?因为argparse 更强大,同时为这些情况提供了出色的语法,而无需您自己解析所有内容。
  • 很抱歉,这很愚蠢:./marvin-cli.py --output=&lt;filename.txt&gt;。由于&lt;&gt; 符号,它会尝试重定向输出和输入。 []&lt;&gt; 对您来说有什么区别,即使这对您来说很明显。 ?
  • [] 和 用于记录需求。通常 [] 表示可选和 必需。

标签: python python-2.7 python-3.x getopt


【解决方案1】:

[]&lt;&gt; 通常用于直观地指示选项要求。通常[xxxx] 表示选项或参数是可选的,&lt;xxxx&gt; 是必需的。

您提供的示例代码处理选项标志,但不是必需的参数。下面的代码应该让您朝着正确的方向开始。

try:
    opts, args = getopt.getopt(sys.argv[1:], "hsv", ["help", "version", "silent", "verbose", "output=", "json"])
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            printUsage(EXIT_SUCCESS)
        elif opt in ("-s", "--silent"):
            VERBOSE = False 
        elif opt in ("--verbose"):
            VERBOSE = True
        elif opt in ("--output"):
            OUTPUTTO = arg
            print("Printing to: ", arg)
        else:
            assert False, "Unhandled option"

    assert len(args) > 0, "Invalid command usage"
    # is there a "<command>" function defined?
    assert args[0] in globals(), "Invalid command {}".format(args[0])

    # pop first argument as the function to call
    command = args.pop(0)
    # pass args list to function
    globals()[command](args)


def ping(args):
    #Getting necessary imports
    import requests
    import time

    # validate arguments
    assert len(args) != 1, "Invalid argument to ping"
    URL = args[0]

    #Setting up variables
    start = time.time()
    req = requests.head(URL)
    end = time.time()

    #printing result
    if VERBOSE == False:
        print("I'm pinging: ", URL)
        print("Received HTTP response (status code): ", req.status_code)

    print("Latency: {}ms".format(round((end - start) * 1000, 2)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 2013-02-26
    • 2018-10-20
    相关资源
    最近更新 更多