Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
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

else:

Pass

But the above code gives me the following error:

File "/usr/local/lib/python2.6/dist-packages/argparse.py", 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

False

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

>>> args.file

True

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
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...