0

I'm trying to use the default value in Python argparse instead of the user specified argument. For example, here's an argument:

parser.add_argument('--fin', default='file.txt')

If a user calls --fin dog, that's obviously not a file, so I want to be able to use the default instead. How would I do that? Does argparse have a function that uses the default instead of the input argument? Also sorry for any typing mistakes, I'm doing this on a phone.

3 Answers 3

4

There's no way to access default arguments using the return value from parser.parse_args(). More importantly, how is "dog" obviously not a file? That's a perfectly valid filename on any modern operating system; file extensions are common but they are by no means required.

The only way to determine if something is or is not a file is by trying to open it. If it fails, either it wasn't a file or you don't have access to it.

In this case, the best solution may be something like:

DEFAULT_FIN = 'file.txt'
parser.add_argument('--fin', default=DEFAULT_FIN)

And later on:

try:
    fd = open(args.fin)
except IOError:
    fd = open(DEFAULT_FIN)

Although I would argue that if the user specifies a filename on the command line and you are unable to open it, then you should print an error and exit.

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

Comments

0

You can:

argument_file = parser.add_argument('--fin', default='file.txt')
args = parser.parse_args()
try:
    fo = open(args.fin)
except:
    fo = open(argument_file.default)
print fo.read()

But solution by larsks with constant seems better.

Comments

0

It is possible to find the default value of an argument if you hang onto the identifier of the argument when you define it. e.g.

In [119]: parser=argparse.ArgumentParser()
In [120]: arg1 = parser.add_argument('--fin', default='default.txt')
In [121]: arg1.default
Out[121]: 'default.txt'

arg1, the value returned by the add_argument method is the Action object that the parser uses. It has all the information that you provided to the method. arg1.default is just one of its attributes.

So you could use arg1.default in your post parse_args code that checks whether args.fin is a valid file or not.

larsks approach is just as good, since you, the user, are defining the default in the first place.

You could also write a custom Action class, or argument type that does this checking. There is a builtin argparse.FileType that tries to open the file, and raises an ArgumentType error if it can't. That could be modified to use the default instead. But this a more advanced solution, and isn't obviously superior to doing your own checking after parsing.

Comments

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.