[Tutor] Using dictionary key values as subprocess arguments

Steven D'Aprano steve at pearwood.info
Thu Aug 1 20:27:17 CEST 2013


Hi Mike, and welcome!

On 02/08/13 03:51, mike at froward.org wrote:
> Hi all,
>
> 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

Would you like us to guess which line gives that error? I love guessing games!

Ah, who am I fooling? Actually I hate them. Please don't expect us to guess where the error is, and don't assume we're going to run your code and see the same error.

- we might not get the same error, for many reasons
- or we might not be willing, or able, to run the code

In general, the most valuable piece of information Python will ever give you is the full traceback it prints when an error occurs, starting with the line "Traceback" and ending at the actual error message. Please copy and paste the entire traceback -- don't retype, simplify, summarize or abbreviate it.

In the meantime, I'm going to guess where your error might be:



> script, targ, switch = argv

Here you assign targ to one of the items of argv. Unless you've done something really weird elsewhere, targ will be a string.


> def on():
>      turnOn = ['ipmitool', '-I', 'lan', '-U', '%(usern)s' % targ,

Here you call the % string interpolation operator and try to look up the name 'usern' from what ought to be a dict or other mapping, but is actually just a string.

> '%(passw)s' % targ,

And again.

>'%(hostn)s' % targ,

And one more time.


You can replicate this error trivially:


py> '%(spam)s' % 'hello'
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: format requires a mapping



Solution: targ is a string, not a mapping. You need to convert it into a mapping.

If anyone suggests you use eval(targ), hit them with a halibut. eval() is not safe with untrusted data, and can execute arbitrary code. Instead, you can either parse targ yourself, or try using ast.literal_eval.



-- 
Steven


More information about the Tutor mailing list