Mateusz
Mateusz

Reputation: 1193

Python - check if arg from arparse was chosen

I would like to check if argument from argsparse was chosen, if not I would like to choose random value for that variable.

Here is example:

parser.add_argument('--tempo', default=120, type=int, help='Tempo of the track')

and one way to do that is for example:

args = parser.parse_args()    
if args.tempo==120: #my default int
    tempo=random.randint(60,350)

But that way when user would like to call my program with for example: main.py --tempo 120, it will also choose random value. How can I check if argument was chosen or not?

Upvotes: 0

Views: 74

Answers (1)

Alex Perrin
Alex Perrin

Reputation: 370

The problem is in the test. if a user chose 120 then it will give a random number. I think the best it to remove the default and check if it is empty.

parser.add_argument('--tempo', default=None, type=int, help='Tempo of the track')
args = parser.parse_args()    
if args.tempo==None: #my default int
    args.tempo=randint(60,350)

Upvotes: 1

Related Questions