argparse, tell if arg was defaulted

Robert Kern robert.kern at gmail.com
Tue Mar 15 12:24:41 EDT 2011


On 3/15/11 9:54 AM, Neal Becker wrote:
> Is there any way to tell if an arg value was defaulted vs. set on command line?

No. If you need to determine that, don't set a default value in the 
add_argument() method. Then just check for None and replace it with the default 
value and do whatever other processing for the case where the user does not 
specify that argument.

parser.add_argument('-f', '--foo', help="the foo argument [default: bar]")

args = parser.parse_args()
if args.foo is None:
     args.foo = 'bar'
     print 'I'm warning you that you did not specify a --foo argument.'
     print 'Using default=bar.'

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list