optparse -- anyway to find if the user entered an option?

Michael Hoffman cam.ac.uk at mh391.invalid
Mon Apr 16 01:01:37 CEST 2007

James Stroud wrote:
> Karthik Gurusamy wrote:
>> Hi,
>> I see that I can provide a default value for an option. But I couldn't
>> find out any way if the user really entered the option or the option
>> took that value because of default. A simple check for value with
>> default may not always work as the user might have manually
>> entered the same default value.
>> Let's assume I want to take in the ip-address using -i <ip-addr>.
>> If user didn't give it explicitly, I am going to use socket interface
>> to figure out this host's IP address.
>> ip_addr_default  = ''
>> parser.add_option("-i", "--ip-address", dest="ip",
>> default=ip_addr_default,
>>            metavar="IP-ADDRESS", help="IP address. default:" +
>>            ip_addr_default + "e.g. --i="
>>            )
>> (options, args) = parser.parse_args()
>> Now if options.ip == ip_addr_default, I still can't be 100% sure that
>> the user did not type -i
>> Any way to figure out from options that the user typed it or not?
>> (The reason I want to know this is if user did not mention -i, I can
>> compute IP later
>> using socket module)
>> I could think of a hack of using None as default and since no user can
>> ever
>> enter a None value, I can be sure that the user didn't provide -i.
>> I'm wondering if there is a cleaner approach -- something like
>> parser.opt_seen("-i")
>> Thanks,
>> Karthik
> Using None wouldn't be a hack, it would rather be a common and 
> straightforward python idiom.

I agree. Also, remember that in optparse the default default (if you 
will) is None.
Michael Hoffman

More information about the Python-list mailing list