This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author paul.j3
Recipients bethard, derelbenkoenig, paul.j3
Date 2018-10-17.17:38:35
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1539797916.05.0.788709270274.issue35005@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2018-10-17 17:38:36paul.j3setrecipients: + paul.j3, bethard, derelbenkoenig
2018-10-17 17:38:36paul.j3setmessageid: <1539797916.05.0.788709270274.issue35005@psf.upfronthosting.co.za>
2018-10-17 17:38:36paul.j3linkissue35005 messages
2018-10-17 17:38:35paul.j3create