Have a python script and using argparse I define some optional arguments that could be given by the user before running the script. I wish to not allow the script to run if the user does not enter any of the optional parameters defined (python example.py -> to give an error message). Any idea on how to do this?
Asked
Active
Viewed 751 times
1
-
I don't want to use required=True for any optional argument. – Thanos Infosec Oct 13 '19 at 18:26
-
Possible duplicate of [Argparse: Check if any arguments have been passed](https://stackoverflow.com/questions/10698468/argparse-check-if-any-arguments-have-been-passed) – Gino Mempin Oct 14 '19 at 00:44
-
1It's a bit confusing (to me, at least). If the script requires an optional parameter to be passed, then it's not optional anymore. – Gino Mempin Oct 14 '19 at 00:48
2 Answers
1
You can use an if
statement with an expression that uses the any
function on all the values of the argument namespace to test if any of the options is given, and if not, print the usage and exit:
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a')
parser.add_argument('-b')
args = parser.parse_args()
if not any(vars(args).values()):
parser.print_usage()
sys.exit()

blhsing
- 91,368
- 6
- 71
- 106
-
Yes, I can handle this case by adding an if statement that uses the any function. But is there any way to do this by using a specific flag when adding the optional arguments? – Thanos Infosec Oct 14 '19 at 07:46
0
First answer is pretty good. Or you could use a simlpe if at the begining of the script.
import sys
if (len(sys.argv) < x):
sys.exit("error message here")
where x is the amount of parameters you are looking for. Otherwise u can use argparser or manually check like
argv[2] == "-b"

Zahovay
- 135
- 9