【问题标题】:Is there any way to take inputs for a option created using parser.add_option, and not take any input for the same option?有没有办法为使用 parser.add_option 创建的选项输入输入,而不为同一选项输入任何输入?
【发布时间】:2020-02-10 05:18:59
【问题描述】:

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

但我进一步要求的是,如果我输入“ 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”才能接受输入并且没有输入。任何帮助表示赞赏。

【问题讨论】:

  • OptionParser 已被弃用,您应该改用argparse.ArgumentParser。使用ArgumentParser,您将能够执行add_argument('--temp', default='celcius')。关于您的第一个问题,您需要发布更多代码。
  • 是的,我正在使用 ArgumentParser。效果很好,谢谢。

标签: python python-3.x command-line-arguments optparse optionparser


【解决方案1】:

使用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

【讨论】:

  • 让我试试
  • 那么我的输入将存储在哪里?没有'dest'选项吗?
  • 它在c.temp,如我的回答所示。 c 是parser.parse_args() 的输出,c.temp 将是--temp 对应的值。
  • 非常感谢。它符合我的要求。
猜你喜欢
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多