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)))
准确地说你的问题是什么?你想添加'--output'到你的getopt分析中吗? –
我认为这个问题很明显......我需要处理多个参数语法,其中参数应该在/ []或<> – geostocker
中您需要使用'getopt'吗?因为'argparse'功能强大得多,同时为这些情况提供了很好的语法,而不必自己解析它。 – poke