【发布时间】: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