I am learning how to use python's *args*
and **kwargs
notations. I am trying to use getattr to pass a variable amount of arguments to a function within another file.
The following code will take a console input, then search what module contains the function put into the console, then execute the function, using arguments.
while True:
print(">>>", end = " ")
consoleInput = str(input())
logging.info('Console input: {}'.format(consoleInput))
commandList = consoleInput.split()
command = commandList[0]
print(commandList) # Debug print
"""Searches for command in imported modules, using the moduleDict dictionary,
and the moduleCommands dictionary."""
for key, value in moduleCommands.items():
print(key, value)
for commands in value:
print(commands, value)
if command == commands:
args = commandList[0:]
print(args) # Debug print
print(getattr(moduleDict[key], command))
func = getattr(moduleDict[key], command, *args)
func()
output = str(func)
else:
print("Command {} not found!".format(command))
output = ("Command {} not found!".format(command))
logging.info('Console output: {}'.format(output))
I try to use a command that takes arguments, such a custom ping command I have made. But, I get this traceback:
Traceback (most recent call last):
File "/home/dorian/Desktop/DEBPSH/DEBPSH.py", line 56, in <module>
func = getattr(moduleDict[key], command, *args)
TypeError: getattr expected at most 3 arguments, got 4
How can I pass more than 3 arguments to the getattr
function?
If you want to pass the arguments to the function, you need to use those in the call to that function. getattr()
knows nothing about the attribute you are retrieving and takes no call arguments.
Do this instead:
func = getattr(moduleDict[key], command)
output = func(*args)
The getattr()
argument only takes the object, the attribute to retrieve from it, and an optional default value if the attribute is not there.
Note that you don't need to call str()
on the function either; at best you maybe want to convert the return value of the function call to string.