I'm using my parser like so
parser.add_argument('owner_type', type=int, required=False, location=location)
I want to be able to send both int
and str
in that field owner_type
.
is there a way to do that?
Didn't find anything in the docs.
You can do something like this:
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Demo.')
parser.add_argument('-e', dest='owner_type', help="help text")
args = parser.parse_args()
owner_type = args.owner_type
if owner_type is not None and owner_type.isdigit():
owner_type = int(owner_type)
print(type(owner_type))
This will only work for int and strings. If you need to handle floats, then you need to handle this case differently as well.
The output:
~/Desktop$ python test.py -e 1
<type 'int'>
~/Desktop$ python test.py -e test
<type 'str'>
~/Desktop$ python test.py
<type 'NoneType'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With