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
如何正确给定的字符串与-c
和decipher(s)
与-s
用不同的发送给适当的功能,即encipher(s)
与-d
,或任选转移?
我见过一些例子,表明你可以手动测试解析器的内容,但不会打败一些目的?
乍一看这看起来可怕的错误,但后来我看到OP实际设置了他的参数解析器以这种方式工作。 – user2357112
谢谢,这似乎做到了! @ user2357112你会建议我设置它吗?我相信这是按预期工作的。 – timss
@timss:好吧,设置解析器可能会很好,因此它需要指定一个'-c'或'-d',但除此之外和'-s' /'s “冲突,看起来不错。 – user2357112