I'm relatively new to Python, but I have a lot of experience in languages like C++ and Java. I am trying to parse a string to a function with parameters. This is what I got so far:
def DimLights(percent = 1.0):
print 'Dimming lights to ' + "{:.2f}".format(percent * 100) + ' percent'
def TurnOffLights():
print 'Turning off lights'
function_mappings = {'DimLights': DimLights,
'TurnOffLights': TurnOffLights}
def select_function():
while True:
try:
return function_mappings[raw_input('Please input the function you want to use')]
except:
print 'Invalid function, try again.'
while True:
function = select_function()
function()
It's working as long as I don't use any parameters, but I can't think of a solution that would work with parameters. Is there any way I can accomplish this?
2 Answers 2
Use str.split() with its maxsplit argument to strip off just the actual command, and argparse to parse the arguments.
5 Comments
str, so you'd use it right on the input. inputline = raw_input(...); command, arguments = inputline.split(maxsplit=1)Try this , Not a complete answer.But You can use it:
def DimLights(percent = 1.0):
print 'Dimming lights to ' + "{:.2f}".format(percent * 100) + ' percent'
def TurnOffLights():
print 'Turning off lights'
function_mappings = {'DimLights': DimLights,
'TurnOffLights': TurnOffLights}
def select_function():
while True:
try:
inp = raw_input('Please input the function you want to use:')
inp = inp.split()
return function_mappings[inp[0]], inp[1]
except:
print 'Invalid function, try again.'
break
function, arg = select_function()
function(float(arg))
# while True:
# function = select_function
# function()
>>>Please input the function you want to use:DimLights 2.0
Dimming lights to 200.00 percent
Note
Put space between function and parameter. Also parameter is required.Otherwise Index error will occur
select_function()that would be in turn passed into the function you select?except:to catch all errors. You probably wantKeyErrorand some select others here. But you probably don't wantSyntaxErroret al.