1

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.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
Junaid
  • 63
  • 1
  • 9
  • 1
    `OptionParser` has been deprecated, you should use `argparse.ArgumentParser` instead. With `ArgumentParser` you'll be able to do `add_argument('--temp', default='celcius')`. With regards to your first problem, you'll need to post more of your code. – Robert Seaman Oct 13 '19 at 09:40
  • Yes i am using ArgumentParser. Works perfectly thanks. – Junaid Oct 13 '19 at 10:24

1 Answers1

2

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
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50