【问题标题】:getopts behaving strangely in pythongetopts在python中表现异常
【发布时间】:2016-07-18 15:14:48
【问题描述】:

我正在使用 getops 进行 args 管理,但由于某种原因,我的 -s 变量不起作用。我的代码如下,以及我得到的输出

try:
  opts, args = getopt.getopt(sys.argv[1:], "hadsp:v", ["help", "all", "display", "single=", "present="])#, "search="])
except getopt.GetoptError as err:
  print(err)
  print "Exiting now, no options entered"
  help()
  sys.exit(2)

if len(opts) == 0:
  print "No options passed"
  help()

print opts
print args

for o, a in opts:
  if o in ("-h", "--help"):
    help()
  elif o in ("-p", "--present"):
    search(a)
  elif o in ("-a", "--all"):
    all_install()
  elif o in ("-s", "--single"):
    if a == '':
      print "crap"
      sys.exit(2)
    single_install(a)
  elif o in ("-d", "--display"):
    display()
  else:
    print "Exiting now, unknown option"
    help()
    sys.exit(2)

输出是

[('-s', '')]
['test']
crap

当我运行程序时:

python file.py -s test

不知道为什么会这样,感谢您的帮助

【问题讨论】:

  • argparse 使用起来更简单安全,
  • 第 2 行末尾有一些杂乱无章的东西,包括一个额外的括号和方括号。奇怪的是口译员不抱怨。
  • 我认为您想使用参数hads:p:v 而不是hadsp:v。 s 后面的冒号表示此开关接受一个参数。
  • @JuanTomas,第 2 行有一个#。最后是评论

标签: python arguments getopts


【解决方案1】:
import argparse

argParser = argparse.ArgumentParser()
argParser.add_argument(
        '-p', '--present', dest='present', help='write help here for this parameter')

args = argParser.parse_args()

if args.present:
    search(a)

使用argparse的示例代码,更易于管理和使用 -h (or) --help 是 argparse 的内置选项

如果你想使用getopt,请参考文档解析选项

https://docs.python.org/2/library/getopt.html

>>> 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')]
>>> args
['a1', 'a2']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-25
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多