2014-01-16 27 views
1

我在理解如何使用argparse和Python 2.7基于参数正确执行函数时遇到了一些问题。该脚本本身用于Caesar's cipher如何使用argparse正确调用函数?

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() 

在哪里使用,就是要:

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

如何正确给定的字符串与-cdecipher(s)-s用不同的发送给适当的功能,即encipher(s)-d,或任选转移?

我见过一些例子,表明你可以手动测试解析器的内容,但不会打败一些目的?

回答

4

该功能将在action,在字符串中s

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

注意与编号参数s-s说法冲突的声明。你只会看到后者。您应该更改其中一个名称 - 例如将编号更改为string,以便短的-s可以保持原样。

+0

乍一看这看起来可怕的错误,但后来我看到OP实际设置了他的参数解析器以这种方式工作。 – user2357112

+0

谢谢,这似乎做到了! @ user2357112你会建议我设置它吗?我相信这是按预期工作的。 – timss

+0

@timss:好吧,设置解析器可能会很好,因此它需要指定一个'-c'或'-d',但除此之外和'-s' /'s “冲突,看起来不错。 – user2357112