Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing in multiple options for argparse in Python

I have been looking at argparse documentation but I am still confused how to use it. I made a python script to get issues from either pmd, checkstyle, or findbugs after a code analysis. Theses issues are also categorized into severities such as major, blocker, and critical.

So I want to be able to pass in two arguments in the form python script.py arg1 arg2 where arg1 would be a combination of p,c,f which stands for pmd, checkstyle, or findbug and arg2 would be a combination of m,c,b which stands for major, critical, and blocker.

So for instance, if I write python script.py pf cb in the terminal, I would get pmd and findbugs issues of critical and blocker severity.

It would be awesome if someone can give me a general structure of how this should go.

Thanks.

like image 959
mrQWERTY Avatar asked Jan 30 '26 15:01

mrQWERTY


2 Answers

Perhaps you'd rather let the user specify the flags more verbose, like this?

python script.py --checker p --checker f --level c --level b

If so, you can use append

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--checker', action='append')
>>> parser.add_argument('--level', action='append')

Then you get a parameter checker and level, both as lists to iterate over.

If you really want to use the combined flags:

for c in arg1:
    run_checker(c, arg2)

Assuming that you just pass the severity levels to the checker in some way.

like image 113
Mattias Backman Avatar answered Feb 02 '26 05:02

Mattias Backman


You could try setting boolean flags if each option is present in an argument:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("pcf", help="pmd, checkstyle, or findbug")
parser.add_argument("mcb", help="major, critical, and blocker")
args = parser.parse_args()

# Use boolean flags
pmd  = 'p' in args.pcf
checkstyle = 'c' in args.pcf
findbug = 'f' in args.pcf

major = 'm' in args.mcb
critical = 'c' in args.mcb
blocker = 'b' in args.mcb

This would work using python script.py pf cb.

Also, just a helpful hint. If you place the following at the top of your python file and then make it executable with chmod +x script.py you can then call the file directly (using a *NIX operating system):

#!/usr/bin/env python
import argparse

...

Now run with ./script.py pf cb or even put it in your path and call script.py pf cb

like image 27
Ewan Avatar answered Feb 02 '26 06:02

Ewan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!