Pregunta

I'm having some problems understanding how to properly execute functions based on arguments using argparse and Python 2.7. The script itself is for Caesar's cipher.

import argparse

def encipher(s):
    pass

def decipher(s):
    pass

def main():
    parser = argparse.ArgumentParser(description="(de)cipher a string using Caesar's cipher")
    group = parser.add_mutually_exclusive_group(required=True)
    parser.add_argument('-s', default=1, help='shift length')
    group.add_argument('-c', dest='action', action='store_const', const=encipher, help='encipher a string')
    group.add_argument('-d', dest='action', action='store_const', const=decipher, help='decipher a string')
    parser.add_argument('s', metavar='string', help='string to (de)cipher')

    # call function (action) with string here

if __name__ == '__main__':
    main()

Where usage is meant to be:

$ ./cipher.py -c "he had a strange car"
if ibe b tusbohf dbs

How do I properly send the given string to the proper function, i.e. encipher(s) with -c and decipher(s) with -d, or optionally with -s with a different shift?

I've seen some examples that indicate you could test the contents of the parser manually, but wouldn't that defeat some of the purpose?

¿Fue útil?

Solución

The function will be in action, the string in s:

args = parser.parse_args()
args.action(args.s)

Note that the declaration of the -s argument conflicts with the numbered argument s. You will only see the latter. You should change one of the names—for example change the numbered one to string, so the short -s can stay as it is.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top