1

现在,当我在命令提示符下键入“ python openweather.py --api= key --city=London --temp=fahrenheit ”时,我会得到所需的华氏温度输出,即使输入了摄氏度(“ --temp=摄氏度“)我得到了所需的摄氏温度输出。

但我进一步要求的是,如果我输入“ python openweather.py --api= key --city=London --temp ”,我需要默认输出摄氏度。问题是我无法为相同的“--temp”执行此操作,因为我不断收到错误消息:“openweather.py: error: --temp option requires 1 argument”对于我尝试的任何事情。

以下是我正在使用的代码:

parser = OptionParser()

parser.add_option('--api', action='store', dest='api_key', help='Must provide api token to get the api request')

parser.add_option('--city', action='store', dest='city_name', help='Search the location by city name')

parser.add_option('--temp', action='store', dest='unit', help='Display the current temperature in given unit')

所以我需要相同的“--temp”才能接受输入并且没有输入。任何帮助表示赞赏。

4

1 回答 1

2

使用nargs='?'并设置您的默认值const='farenheit'

import argparse

parser  = argparse.ArgumentParser()
parser.add_argument('--temp', '-t', nargs='?', type=str, const='farenheit')

c = parser.parse_args()

# Show what option was chosen.
# If --temp was not used, c.temp will be None
# If -- temp was used without argument, the default value defined in 
# 'const='farenheit' will be used.
# If an argument to --temp is given, it will be used.

print(c.temp)

样品运行:

thierry@tp:~$ python test.py
None

thierry@tp:~$ python test.py --temp
farenheit

thierry@tp:~$ python test.py --temp celsius
celsius
于 2019-10-13T09:39:10.577 回答