Check if argparse optional argument is set or not

后端 未结 9 1552
臣服心动
臣服心动 2020-12-13 11:48

I would like to check whether an optional argparse argument has been set by the user or not.

Can I safely check using isset?

Something like this:

<         


        
9条回答
  •  情深已故
    2020-12-13 12:08

    Here is my solution to see if I am using an argparse variable

    import argparse
    
    ap = argparse.ArgumentParser()
    ap.add_argument("-1", "--first", required=True)
    ap.add_argument("-2", "--second", required=True)
    ap.add_argument("-3", "--third", required=False) 
    # Combine all arguments into a list called args
    args = vars(ap.parse_args())
    if args["third"] is not None:
    # do something
    

    This might give more insight to the above answer which I used and adapted to work for my program.

提交回复
热议问题