paul
paul

Reputation: 13481

Get command line parameters with argparse

I´m trying to use argparse of Python but I cannot get a command line parameter.

Here my code:

DEFAULT_START_CONFIG='/tmp/config.json'

parser = argparse.ArgumentParser(description='Start the Cos service and broker for development purposes.')
parser.add_argument('-c', '--config', default=DEFAULT_START_CONFIG, action=FileAction, type=str, nargs='?',
                help='start configuration json file (default:' +  DEFAULT_START_CONFIG + ')')

args = parser.parse_args()

But then when I run my python script like:

./start.py -c /usr/local/config.json

Instead of getting this path it is getting the default value defined (/tmp/config.json).

print args.config ---> "/tmp/config.json"

What I´m doing wrong here?

Upvotes: 0

Views: 656

Answers (1)

user3159253
user3159253

Reputation: 17455

The standard documentation doesn't mention FileAction. Instead there's a class FileType intended for type argument, not for action.

So I would write something like this:

DEFAULT_START_CONFIG='/tmp/config.json'

parser = argparse.ArgumentParser(description='Start the Cos service and broker for development purposes.')
parser.add_argument('-c', '--config', default=DEFAULT_START_CONFIG,
    type=argparse.FileType('r'), help='start configuration json file')
args = parser.parse_args()
print(args)

This gives me the following:

$ python test3.py
Namespace(config=<open file '/tmp/config.json', mode 'r' at 0x7fd758148540>)
$ python test3.py -c
usage: test3.py [-h] [-c CONFIG]
test3.py: error: argument -c/--config: expected one argument
$ python test3.py -c some.json
usage: test3.py [-h] [-c CONFIG]
test3.py: error: argument -c/--config: can't open 'some.json': [Errno 2] No such file or directory: 'some.json'
$ touch existing.json
$ python test3.py -c existing.json
Namespace(config=<open file 'existing.json', mode 'r' at 0x7f93e27a0540>)

You may subclass argparse.FileType to something like JsonROFileType which would check if the supplied file is actually a JSON of expected format etc, but this seems to be out of the scope of the question.

Upvotes: 1

Related Questions