paul j3 <ajipa...@gmail.com> added the comment:

If I define a 'type' function like:

def readdata(astr):
    if astr.startswith('@'):
        with open(astr[1:], 'r') as f:
            d = json.load(f)
            return d
    else:
        return astr

I can use it to load a json file, or use the string directly:

In [59]: parser = argparse.ArgumentParser()
In [60]: parser.add_argument('-d','--data', type=readdata);
In [61]: parser.parse_args(['-d','@foo.json'])
Out[61]: Namespace(data={'foo': 12, 'bar': 'twelve'})
In [62]: parser.parse_args(['-d','xxx'])
Out[62]: Namespace(data='xxx')

This seems to behave as the 'curl' and 'ansible' examples you give, where the 
interpretation of the '@' is option specific.

A fully functional version of this type function needs to catch possible errors 
(not a file, not proper json, etc) and raise a ValueError or 
argparse.ArgumentTypeError.

The fact that 'curl -d' uses the '@', and 'fromfile_prefix_args' uses '@' in 
the documentation, should be seen as purely coincidental.  argparse would be 
just as happy using '#' or '%' as fromfile-prefix characters, just so long as 
the shell passes them unchanged to 'sys.argv'.  Conversely a type function can 
pay attention to special characters without needing to define them in the 
parser definition.

argparse doesn't define many custom 'type' functions.  Mostly it depends on 
people using stock Python functions like 'int' and 'float', or writing their 
own functions.  This keeps things simple for the common uses, while giving more 
advanced users a lot of flexibility.

This '@file' sensitivity could also be built into a custom Action subclass.  
There too, argparse has defined a set of common cases, but lets the users 
customize to their heart's content.

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue35005>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to