[Tutor] Odd problem with variable substitution and command execution

Kent Johnson kent37 at tds.net
Wed Apr 13 19:55:01 CEST 2005


Robert, Andrew wrote:
> Hi Everyone,
> 
> I am trying to do an MQ inquiry but I am having mixed results.
> 
> If I do the command direct via a print statement like the one below, it
> works,
> 
> 
> print 'Queue Description:\t' , q.inquire(CMQC.MQCA_Q_DESC)
> 
> 
> When I try to cycle through an array of command line supplied keys, it
> fails.
> 
> 
> while counter < arg_array_size:
>     arg1=valid_keys[sys.argv[counter]]
>     arg2 = 'q.inquire(CMQC.'+valid_keys[sys.argv[counter]]+')'
>     print arg1,"     ",arg2
>     counter = counter +1

You are confusing strings with executable code. What you are doing here is essentially
print 'MQCA_Q_DESC' , 'q.inquire(CMQC.MQCA_Q_DESC)'

Note the quotes around the second string - not very exciting.

You could use eval() to get around this but there are better ways. You just need to get an attribute 
of CMQC by name, then call q.inquire() with that attribute. Something like this should work:

while counter < arg_array_size:
     arg1=valid_keys[sys.argv[counter]]

     # if arg1 is the string "MQCA_Q_DESC" then the next line is the same
     # as saying queryParam = CMQC.MQCA_Q_DESC
     queryParam = getattr(CMQC, arg1)

     # Now we can use queryParam directly
     arg2 = q.inquire(queryParam)
     print arg1,"     ",arg2
     counter = counter +1

I have no way to test this so write back if you have trouble with it.

Kent



More information about the Tutor mailing list