Simple question: How can I pass an arbitrary list of args to a python callable?
Let's say I want to invoke a function from the command line, like so:
my_script.py foo hello world
with the following script:
import myfuncs
f = getattr(myfuncs, sys.args[1])
if f and callable(f):
# This is the bit I don't know. I effectively want f(sys.args[2:])
I'm sure there's a way to do this, but I must be overlooking it.
You are looking for sequence unpacking. I.e. f(*sys.argv[2:])
Yep, check out the section Unpacking argument lists in the docs.
For your particular use, it could be something like this
def f(a, b, c):
print a, b, c
stuff = ['f',2,3,4]
f(*stuff[1:]) ### equivalent to f(2,3,4)
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