简体   繁体   中英

How can i pass an optional parameter to a python class using argparse function in python

I have a python script script.py that has the below init function

def __init__(self):
    """init method for the class."""
    parser = argparse.ArgumentParser(description="test")
    parser.add_argument('-u', '--user', dest='user',
                        default='', required=True,
                        action="store", help="the script running user")
    parser.add_argument('-i', '--url', dest='url',
                        default="", required=True,
                        action="store", help="url")
    parser.add_argument('-e', '--env', nargs='*',
                        dest='env',help="the env type")
    parsers = parser.parse_args()
    self.user = parsers.user.strip()
    self.url = parsers.url.strip()
    self.env = parsers.args.env.strip()

The env type stores 2 values either test or prod . The env parameter should be optional, if values is not provided it should take default values as prod or else it should store any of the values provided(test/prod). if no value for env is passed, the default value should be prod I tried making the env param as optional using nargs but when my script executes it throws me the error.

Traceback (most recent call last):
  File "script.py", line 185, in <module>
    obj = script()
  File "script.py", line 66, in __init__
    self.env_type = parsers.args.env_type.strip()
AttributeError: 'Namespace' object has no attribute 'args'

I am executing my script as

python script.py -u <user> -i <url> -e <env>

Ideally i want my script to execute even when -e option is not provided. How should i change my script?

If you just want the env to be either "prod" or "test", you can use choices ( docs ), with a default value:

parser.add_argument('-e', '--env', choices=['prod', 'test'], default='prod', help="the env type")

This will raise an error if something else is passed to --env .

Note that flags with dashes like -e --env are assumed optional in argparse ( docs )

Shouldn't it be without args ?:

self.env = parsers.env.strip()

also you could handle the AttributeError:

try:
    self.env = parsers.env.strip()
except AttributeError:
    self.env = 'prod'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM