此问题正在跟进link
#!/usr/bin/env python
import argparse
import sys
import itertools as IT
from snemail import *
parser = argparse.ArgumentParser(
prog='snemail',
usage='%(prog)s [-h] [--usage] action target [input]',
epilog="refer to '%(prog)s usage' for examples of how to run snemail"
)
parser.add_argument('action', metavar='action', nargs='?', type=str, choices=('list', 'add', 'remove'), help="list | remove | add")
parser.add_argument('target', metavar='target', nargs='?', type=str, choices=('domain', 'forwarding', 'transport', 'user', 'all'), help="domain | forwarding | transport | user")
parser.add_argument('input', nargs='?', type=str, default=None, help="required input to go with the 'remove' and 'add' flags. 'list' requires no input field")
parser.add_argument('--usage', action='store_true', help="show usage examples for snemail")
args = parser.parse_args()
if args.usage:
usage()
sys.exit(0)
if args.action is None or args.target is None:
parser.print_help()
sys.exit(0)
if args.target == 'all':
all_list()
sys.exit(0)
if len(sys.argv) >= 3:
input = args.input
input = input.split(',')
else:
input = None
def usage():
print 'usage info here'
targets = 'domain forwarding transport user'.split()
actions = 'list add remove'.split()
dispatch = {key:globals()['%s_%s' % key] for key in IT.product(targets, actions)}
if input is not None:
dispatch.get((args.target, args.action), usage)(input)
elif args.action is not None and args.target is not None:
parser.print_help()
sys.exit(0)
这段代码可能会让专业python-coder的皮肤爬行,但它适用于我,在Python 2.7(我用于我的开发机器),但当我尝试在机器上执行此代码时将在生产中运行此代码,它没有执行代码,因为
dispatch = {key:globals()['%s_%s' % key] for key in IT.product(targets, actions)}
在2.7中不起作用。
亲爱的互联网大师,如何在Python 2.6上完成这项工作? (因为升级到2.7不是一个选项,但更重要的是我想编写适当的Python)
答案 0 :(得分:3)
将dict()
与生成器表达式一起使用:
dispatch = dict((key, globals()['%s_%s' % key]) for key in IT.product(targets, actions))
生成器表达式创建(key, value)
2值元组;这适用于2.6和2.7(或python 3,就此而言)。