I want to pass function definition to a python command line script. What is the best way to do this? I am using python 2. Suppose i have a script like this:
#myscript.py
x = load_some_data()
my_function = load_function_definition_from_command_line()
print my_function(x)
And i want to call it like this: python myscript.py 'def fun(x): return len(x)'
How do i perform the load_function_definition_from_command_line part ?
I imagine a workaround:
But I am sure there must be a better way.
You can use eval to run code defined in a string. Like so:
import sys
x = load_some_data()
function = eval("".join(sys.argv[1:]))
print(function(x))
With your specific example though you might have to use something like lambda x: len(x)
As @Jan-Spurny rightly points out: "Never, never, never use eval unless you're absolutely sure there is no other way. And even then you should stop and think again."
In my mind the better strategy would be to turn the data loader and executor into a module with a method that takes a function as an argument and runs the desired code. The end result something like this:
import data_loader_and_executor
def function(x):
return len(x)
data_loader_and_executor.run(function)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With