Last active
January 4, 2017 16:02
-
-
Save JZfi/e2bf0138e454dd2d9218c8ace0279015 to your computer and use it in GitHub Desktop.
Call a python function with a dict of arguments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
# Call a python function with a dict of arguments | |
# The dict can contain excess values. This function only picks the supported ones and if they exist in the passed arguments | |
def call_python_function(module, function_name, argument_dictionary): | |
funcpointer = getattr(module, function_name) | |
# Find what arguments the module's function takes | |
argspec = inspect.getargspec(funcpointer) | |
# Remove the self that is a python self-reference | |
argspec.args.remove('self') | |
# argspec.args is now an empty list if the func doesn't take any arguments | |
# Create a dictionary with the arguments taken from the passed data (if the key exists) | |
args = {argname: argument_dictionary[argname] for argname in argspec.args if argname in argument_dictionary.keys()} | |
# Call the command with the dictionary passed as arguments | |
return funcpointer(**args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example of a minimal Ansible module that can be used to call python functions in some utility library:
Save the above as
library/world_control.py
and replace the instance creation line with some magic library initialization call.The ansible task below calls our imaginary python function
shutdown_everything(target_list, white_gloves=True, force=False)
in that library.