rebar rebar - 1 year ago 77
Python Question

python: how can I pass a variable to a function with only the string name

I'm interacting with a relatively complex program and putting a GUI on it to issue commands. I made up a simple example which I think demonstrates the problem. I know what parameters need to be passed to issue a command but I will only be able to get them as strings.

There are hundreds of commands with different return values that I get dynamically, but this is one example what I can get back when I pass a command ID

def get_command_vars(commandID = None):
if commandID == '0x4F':
return [['mode', '16bits'], ['seconds', '8bits']]

def issueMyCommand(commandID = None):
commandParameters = get_command_vars(command=0x4F)

commandParameters tells me that the parameters for this command are mode and seconds, but they are strings

commandParm_1 = commandParameters[0][0] # 'mode'
commandParm_2 = commandParameters[1][0] # 'seconds'

>get User Input from the gui to pass to issuetheCommand
input1 = getinputEntry1() # this is the 'mode' value, e.g., 8
input2 = getinputEntry2() # this is the 'seconds' value, e.g., 14

I have the values to pass from the user input but I don't know how to pass them to the function since I only have the variables as strings, i.e.'mode' and 'seconds'

c = issueTheCommand(mode = input1, seconds = input2)

this command format will change based on the parameter types from get_command_vars, so it could be 'count', 'datalength', 'milliseconds, 'delay', etc

@sberry - actually the user input values are what will be passed with mode and seconds. the 16bits and 8 bits doesn't really come into play here. I'm trying to do this without changing the format that "issueTheCommand" function is expecting if possible. the way I issue it now looks like this:
c = issueTheCommand(mode = 8, seconds = 14). i don't think it will take a dict?

Answer Source

If my comment to your question is what you are after then perhaps using a dictionary as key-word arguments would work for you.

>>> def issueTheCommand(mode, seconds):
...     print mode, seconds
>>> issueTheCommand(**{"mode": "16bits", "seconds": "8bits"})
16bits 8bits
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download