2016-10-02 43 views
0

所以我正在做一個我正在使用的python類的任務,但已經卡住了一些我無法找到任何進一步信息(無論是在SO,Google還是在課件)。Getopt多參數語法

我需要如何處理與多種類型的語法參數幫助 - 像[參數]和< ARG>,這是我一直無法找到任何進一步的信息。

下面是一個應用案例,應該工作。

>>> ./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如何工作的片段:

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))) 
+0

準確地說你的問題是什麼?你想添加'--output'到你的getopt分析中嗎? –

+0

我認爲這個問題很明顯......我需要處理多個參數語法,其中參數應該在/ []或<> – geostocker

+0

中您需要使用'getopt'嗎?因爲'argparse'功能強大得多,同時爲這些情況提供了很好的語法,而不必自己解析它。 – poke

回答

1

[]<>通常用於直觀地表示選項要求。通常,[xxxx]表示選項或參數是可選的並且需要<xxxx>

您提供的示例代碼處理選項標誌,但不是必需的參數。下面的代碼應該讓你開始正確的方向。

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)))