pythonpython-3.xcommand-line-argumentsoptparseoptionparser

Is there any way to take inputs for a option created using parser.add_option, and not take any input for the same option?


Now when I type " python openweather.py --api=key --city=London --temp=fahrenheit " in command prompt, I get the desired output of temperature in fahrenheit or even if celcius is entered (" --temp=celcius ") I get the desired output of temperature in celcius.

But what I further require is that if I type " python openweather.py --api=key --city=London --temp " , I require an output in celcius as default. And the problem is that I am unable to do it for the same '--temp' because I keep getting the error : " openweather.py: error: --temp option requires 1 argument " for any thing I try.

Following is the code I am using:

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')

So I require the same '--temp' to be able to take inputs and be left without inputs. Any help is appreciated.


Solution

  • Use nargs='?' and set your default value with 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)
    

    Sample runs:

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