0

This question is following up on 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)

This code will probably make the skin crawl of a professional python-coder, but it works for me, on Python 2.7 (which I use for my development-machine), but when I tried to execute this code on the machine that is going to run this code in production, it didn't execute the code because

dispatch = {key:globals()['%s_%s' % key] for key in IT.product(targets, actions)}

doesn't work in 2.7.

Dear gurus of the internet, how to make this work on Python 2.6? (because upgrading to 2.7 is not an option, but more importantly I'd like to write proper Python)

Community
  • 1
  • 1
Peter van Arkel
  • 519
  • 1
  • 5
  • 14

1 Answers1

3

Use a dict() with a generator expression:

dispatch = dict((key, globals()['%s_%s' % key]) for key in IT.product(targets, actions))

The generator expression creates (key, value) 2-value tuples; this works in both 2.6 and 2.7 (or python 3, for that matter).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343