Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (1.6k points)

I have created a script using argparse .The script takes a configuration file name as an option and allows the user to specify whether they want to proceed totally the script or only to stimulate it.

 The args which is to be passed : ./script -f config_file -s or ./script -f config_file.

 It is working fine for the -f config_file part, but It keeps asking me for arguments for the -s which is optional and should not be followed by any. 

I tried this code:

parser = argparse.ArgumentParser()

parser.add_argument('-f', '--file')

#parser.add_argument('-s', '--simulate', nargs = '0')

args = parser.parse_args()

if args.file:

    config_file = args.file

if args.set_in_prod:

        simulate = True



But the above code gives me the following error:

File "/usr/local/lib/python2.6/dist-packages/", line 2169, in _get_nargs_pattern

nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)

TypeError: can't multiply sequence by non-int of type 'str'

 And same error with ‘ ‘ instead of 0. 

1 Answer

0 votes
by (10.9k points)

The “action” keyword determines how to handle the command-line arguments.

There are various actions available in Python some of them are:

1. ‘store’ : It stores the value of the arguments.

2. ’store_const’ : It stores the value which is specified by the const keyword argument.

3. ‘store_true’ and ‘store_false’ : These are used to store the value “True” and “False” respectively. These are special cases of ‘store_const’ .

 To solve your problem you must use the ‘store_true’ action: 

>>> from argparse import ArgumentParser

>>> parser = ArgumentParser()

>>> _ = parser.add_argument('-f', '--file', action='store_true')

>>> args = parser.parse_args()

>>> args.file


>>> args = parser.parse_args(['-f'])

>>> args.file


Related questions

0 votes
1 answer
0 votes
1 answer
+1 vote
1 answer
0 votes
1 answer
asked Jul 5, 2019 in Python by selena (1.6k points)
0 votes
1 answer

Browse Categories