Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke python callable with an arg list

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.

like image 823
Toji Avatar asked Apr 28 '26 11:04

Toji


2 Answers

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)
like image 40
Andrew Jaffe Avatar answered May 01 '26 01:05

Andrew Jaffe