Replace empty strings on argparse to None
Specify the command line argument as having type str
with default None
, for example:
parser.add_argument('-j', '--jfile', default=None, type=str)
Then if the user omits -j
entirely then you will get None
back. But if the user puts -j
on the command line with nothing after it, they will get the error argument -j/--jfile: expected one argument and they will have to supply a string value to get past this. So you should always get either None
or a non-empty string.
The type argument of ArgumentParser.add_argument()
is a function that "allows any necessary type-checking and type conversions to be performed." You can abuse this:
import argparse
def nullable_string(val):
if not val:
return None
return val
parser = argparse.ArgumentParser()
parser.add_argument('--foo', type=nullable_string)
print(parser.parse_args(['--foo', ''])
Output:
Namespace(foo=None)