选择性结构上的python函数argeparse:无法识别的参数

时间:2019-07-07 06:33:19

标签: python python-3.x function argparse

我正在使用基于argparse的函数,以将其用于不同的选项以及对此选项的计算。

这很完美:

def parseArgument(argv, abv, name, hdescription):
  parser=argparse.ArgumentParser(description='Show calculated data')
  parser.add_argument(abv,
                      name, 
                      help = hdescription, 
                      action = "store_true",
                      )
  args=parser.parse_args()
  return args

args_h = parseArgument(['-y'],"-y", "--humedity", "Calculate humedity average", False)

if args_h.humedity: 
  print("\nHUMEDITY CYCLE: ", DPV(w, 2, HR_CYCLE, count_NC))

但是当我尝试添加更多选项args_t.temperature)时,我会得到error: unrecognized argument -y

def parseArgument(argv, abv, name, hdescription):
  parser=argparse.ArgumentParser(description='Show calculated data')
  parser.add_argument(abv,
                      name, 
                      help = hdescription, 
                      action = "store_true",
                      )
  args=parser.parse_args()
  return args

args_h = parseArgument(['-y'],"-y", "--humedity", "Calculate humedity average", False)

args_t = parseArgument(['-t'],"-t", "--tempature", "Calculate temp average", False)

if args_h.humedity: 
  print("\nHUMEDITY CYCLE: ", DPV(w, 2, HR_CYCLE, count_NC))
elif args_t.temperature:
  print("\nTEMPERATURE CYCLE", DPV(w,1,TR_CYCLE,count_NC)) 

我希望在argparse函数中将此结构与其他选项一起使用:

if args_h.humedity:
  ...
elif args_t.temp:
  ...
elif args_other.other:
  ...

当我运行script.py -y

usage: cycle.py [-h] [-t]
cycle.py: error: unrecognized arguments: -y```

**When I use script.py -h**
```usage: cicly.py [-h] [-y]
optional arguments:
  -h, --help     show this help message and exit
  -y, --humedity  Calculates humedity average
```
**doesn't show [-t]**

1 个答案:

答案 0 :(得分:2)

您需要像这样将每个选项立即添加到解析器中:

import sys
import argparse
def parse_arguments():
    parser = argparse.ArgumentParser(description='Show calculated data')
    parser.add_argument('-y', '--humidity', 
                        help='Calculate humidity average', 
                        action="store_true")
    parser.add_argument('-t', '--temperature', 
                        help='Calculate temperature average', 
                        action="store_true")
    args = parser.parse_args()
    return args, parser

def main():
    args, parser = parse_arguments()
    if len(sys.argv) < 2:
        return parser.print_help()
    if args.temperature:
        print('will calculate temperature')
    if args.humidity:
        print('will calculate humidity')

if __name__ == "__main__":
    main()

不带任何参数调用python calc.py会给出

> python args.py
usage: calc.py [-h] [-y] [-t]

Show calculated data

optional arguments:
  -h, --help         show this help message and exit
  -y, --humidity     Calculate humidity average
  -t, --temperature  Calculate temperature average

带有一些开关:

> python calc.py -y -t
will calculate temperature
will calculate humidity