因此,我正在编写一个python类中的作业,但是我一直无法找到更多的信息(无论是Google还是课件)。
我需要帮助如何使用多种类型的语法来处理参数,比如arg和< 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)))发布于 2016-10-02 15:53:14
[]和<>通常用于直观地表示选项要求。通常,[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)))https://stackoverflow.com/questions/39817973
复制相似问题