Pranav Shankar
Pranav Shankar

Reputation: 51

Default argument for argparse

So I have a file abc.py

--a string
--b string

as optional arguments I want to be able to do

abc.py string --> func1
abc.py string --a string --> func1 and func2
abc.py string --a string --> func1 and func2
abc.py --a string --> func2

and so on I managed to get --a and --b working (separately and together) I am not able to be abc.py string working am I supposed to use argv and argparse in conjunction?

edit: I guess my question is I want to handle the case when default does not have any argument, i.e. I run --> abc.py --a hello<-- and I need them to run in any combination (none specified, default and a specified, a and b specified, only default specified etc)

if __name__ == '__main__':
parser=argparse.ArgumentParser()
parser.add_argument("default", help="default")
parser.add_argument("--a","-a", help="a")
parser.add_argument("--b","-b", help="b")
args=parser.parse_args()
if args.a:
    a_func(args.a)                   
if args.b:
    b_func(args.b)
default_func(args.default)

edit: okay guys I got it working, what I did was

parser=argparse.ArgumentParser()
parser.add_argument("default",nargs="*", help="default")
parser.add_argument("--a","-a",nargs="*", help="a")
parser.add_argument("--b","-b",nargs="*", help="b")
args=parser.parse_args()
a_func(args.a)                   
b_func(args.b)
default_func(args.default)

Now I just check if the list is empty or not inside the function and I can process multiple arguments in the func as well

Upvotes: 2

Views: 253

Answers (1)

mertyildiran
mertyildiran

Reputation: 6611

You should you sys module of Python standard libraries:

#!/usr/bin/env python

import sys

print sys.argv[1] // first argument

Which will print string output on the command line in your case.

The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string. sys.argv

Upvotes: 1

Related Questions