0

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?

4
  • Hopefully, DEFAULT_START_CONFIG='/tmp/config.json' and it's defined within the script ? Commented Jan 26, 2016 at 10:05
  • yes, has quotes and it´s defined in the script Commented Jan 26, 2016 at 10:09
  • I'm surprised it ran without error, with that unknown FileAction. Commented Jan 27, 2016 at 2:04
  • It was not unknown, it´s just that a colleague did that class, and I did not notice. Commented Jan 27, 2016 at 9:14

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That was exactly the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.