[Tutor] Using dictionary key values as subprocess arguments

Alan Gauld alan.gauld at btinternet.com
Thu Aug 1 23:30:56 CEST 2013


On 01/08/13 18:51, mike at froward.org wrote:

> I'm trying to use dictionary key values as arguments being passed via
> subprocess. The following is supposed to use argv arguments passed for the
> target host, and direction to turn the ipmi interface up on or off. When I
> run it I get an error about TypeError: format requires a mapping

You need to provide a dict to the form,at operator you are passing a 
string which (you hope!) represents one of your dicts.

>
> script, targ, switch = argv
>
> ren      = {'hostn':'ren.ipmi', 'usern':'Admin', 'passw':'p0w1r'}
> stimpy   = {'hostn':'stimpy.ipmi', 'usern':'Admin', 'passw':'p0w1r'}
> lrrr     = {'hostn':'lrrr.ipmi', 'usern':'ADMIN', 'passw':'p0w1r'}
> kif      = {'hostn':'kif.ipmi', 'usern':'ADMIN', 'passw':'p0w1r'}
> ndnd     = {'hostn':'ndnd.ipmi', 'usern':'ADMIN', 'passw':'p0w1r'}
> zapp     = {'hostn':'zapp.ipmi', 'usern':'ADMIN', 'passw':'p0w1r'}

Rather than using named variables it would be better to make the hosts a 
dicty too keyed by host name:

hosts = { 'ren':{'hostn':'ren.ipmi',
                	 'usern':'Admin',
                  'passw':'p0w1r'},
           'stimpy':{'hostn':'stimpy.ipmi',
                     'usern':'Admin',
                     'passw':'p0w1r'}
            # etc...
           'zapp':{'hostn':'zapp.ipmi',
                   'usern':'ADMIN',
                   'passw':'p0w1r'}
         }

Now you can pass the dict into the format with:

      turnOn = ['ipmitool', '-I', 'lan',
                '-U', '%(usern)s' % hosts[targ],
                '-P', '%(passw)s' % hosts[targ],
                '-H', '%(hostn)s' % hosts[targ],
                'chassis', 'power', 'on']

And while you are at it catch invalid host names by using a try/except 
block to catch KeyErrors

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list