Python 有没有办法为使用parser.add_选项创建的选项获取输入,而不为同一选项获取任何输入?
现在,当我在命令提示符中键入“python openweather.py--api=key--city=London--temp=fahrenheit”时,我会得到所需的温度输出,单位为华氏温度,或者即使输入了celcius(“--temp=celcius”),我也会得到所需的温度输出单位为celcius 但我进一步需要的是,如果我键入“python openweather.py--api=key--city=London--temp”,我需要一个默认的celcius输出。 问题是,我无法对同一个'--temp'执行此操作,因为我不断收到错误:“openweather.py:error:--temp选项需要1个参数”对于我尝试的任何事情 以下是我正在使用的代码:Python 有没有办法为使用parser.add_选项创建的选项获取输入,而不为同一选项获取任何输入?,python,python-3.x,command-line-arguments,optparse,optionparser,Python,Python 3.x,Command Line Arguments,Optparse,Optionparser,现在,当我在命令提示符中键入“python openweather.py--api=key--city=London--temp=fahrenheit”时,我会得到所需的温度输出,单位为华氏温度,或者即使输入了celcius(“--temp=celcius”),我也会得到所需的温度输出单位为celcius 但我进一步需要的是,如果我键入“python openweather.py--api=key--city=London--temp”,我需要一个默认的celcius输出。 问题是,我无法对同一
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'能够接受输入,而不需要输入。非常感谢您的帮助。使用
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
OptionParser
已被弃用,应改用argparse.ArgumentParser
。使用ArgumentParser
您将能够执行添加参数('--temp',default='celcius')
。关于第一个问题,您需要发布更多代码。是的,我正在使用ArgumentParser。非常好,谢谢。让我试试。我的输入将存储在哪里?没有“dest”选项吗?它位于c.temp
中,如我的回答所示c
是解析器的输出。parse_args()
,而c.temp
将是--temp
对应的值。非常感谢。它根据我的要求工作。