argmap - simple argument parsing
This module aims to greatly simplify adding argument parsing to existing code and simple scripts. Detailed documentation can be found here.
To generate the documentation, you can use make -C docs
. Note, this requires
the sphinx documentation generator.
To run the tests, execute nosetests
. Note, this requires the nose
unittesting tool.
Example
It uses inspection to figure out how to wrap a function for the command-line, consider the following example:
import argmap, json
@argmap.arg("set", [(str, str)], "overwrite the key with a new value")
def update_json(json_file, set=[]):
"""Update a json file by setting a number of keys to the given values.
"""
with open(json_file, "r") as fobj:
desc = json.load(fobj)
for (key, value) in set:
desc[key] = value
with open(json_file, "w") as fobj:
json.dump(desc, fobj)
if __name__ == "__main__":
argmap.argmap(update_json)
This script can be used by importing it and using the method or by running it directly from the command line, ala:
cat << EOF > example.json
{
"a": "a",
"b": "b"
}
EOF
python -m update_json example.json --set "a" "1" --set "b" "2"
cat example.json
Using classmethods
To use classmethods as the commandline entry you have to make sure to get the order of the deocrators right. The argmap decorators need to be applied first and then followed by the classmethod decorator.
For example:
class CalculateSum(object):
@classmethod
@argmap.arg("a", int)
@argmap.arg("b", int)
def main(cls, a, b):
print a + b