gpt4 book ai didi

python - 这个for循环的目的是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 15:35:09 25 4
gpt4 key购买 nike

我正在阅读“Black Hat Python”一书,当前的事件是构建一个 netcat 替代品。要设置选项,使用“getopt”。我很困惑为什么在 for 循环中使用 o,a 来检查选项?

  if not len(sys.argv[1:]):
usage()

# read the command line options
try:

opts, args = getopt.getopt(sys.argv[1:],"hle:t:p:cu:", \
["help", "listen", "execute", "target", "port", "command", "upload"])
except getopt.GetoptError as err:
print(str(err))
usage()

for o,a in opts:
if o in ("-h","--help"):
usage()
elif o in ("-l", "--listen"):
listen = True
elif o in ("-e", "--execute"):
execute = a
elif o in ("-c", "--commandshell"):
command = True
elif o in ("-u", "--upload"):
upload_destinaton = a
elif o in ("-t", "--target"):
target = a
elif o in ("-p", "--port"):
port = int(a)
else:
assert False,"Unhandled Option"

最佳答案

如果您查看 documentation page for python getopt ,有一个例子可以证明这一点:

>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] # <--- HERE
>>> args
['a1', 'a2']

opts(在您的问题中)对应于上面示例中的 optlist

getopt 返回一个元组列表作为第一个返回值(和一个列表作为第二个),因此通过使用 for o,a in opts,代码拆分这些元组在每次循环迭代期间向上。

关于python - 这个for循环的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55271212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com