0

I have a program which can take in a few different arguments, and depending on what the argument is that is passed, that function is called in the python program. I know how to use sys.arv, and I have used argparse before, however I am not sure how to go about accomplishing the following with argparse..

Possible arguments: func1, func2, func3

Program could be executed with either of the following:

python myprogram func1
python myprogram func2
python myprogram func3

Therefore the arg passed correlates to a function in the program. I do not want to include any dashes in the arguments so nothing like -func1 or -func2...etc.

Thank you!

1 Answer 1

1
 parser.add_argument('foo', choices=['func1','func2','func3'])

will accept one string, and raise an error if that string is not one of the chocies. The results will be a namespace like

 Namespace(foo='func1')

and

 print(args.foo)
 # 'func1'

Is that what you want?

The subparsers mechanism does the same thing, but also lets you define added arguents that can differ depending on which subparser is given.

Sign up to request clarification or add additional context in comments.

7 Comments

Yes, that was much simpler than I originally thought it would be. Thank you!
Just one question...How can I make a call to the function based on the arg that was passed? Something like args.foo() or foo() ?
You have to match the string with the function, for example with a dictionary. dd = {'func1':func1, 'func2':func2}; dd[args.foo](). The docs describes a different mechanism when using subparsers (using setdefault).
Awesome, that makes sense. Thank you!
Alternatively if the functions are in a module called module then you could call it as getattr(module, args.foo)(). Normally you don't like to look up code in a module using user input, because they could type anything, but in this case you've explicitly constrained their choices already so it's not so bad. If the functions are in the current module you can get it as sys.modules[__name__], or do globals()[args.foo].
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.