【问题标题】:Invoke python callable with an arg list使用 arg 列表调用 python 可调用对象
【发布时间】:2010-11-15 16:43:04
【问题描述】:

简单问题:如何将任意 args 列表传递给 python 可调用对象?

假设我想从命令行调用一个函数,如下所示:

my_script.py foo hello world

使用以下脚本:

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:])

我确信有办法做到这一点,但我必须忽略它。

【问题讨论】:

    标签: python callable


    【解决方案1】:

    您正在寻找sequence unpacking。 IE。 f(*sys.argv[2:])

    【讨论】:

    • 谢谢,一旦你知道它们叫什么,这些东西总是很简单的,嗯?
    【解决方案2】:

    是的,请查看文档中的 Unpacking argument lists 部分。

    对于您的特定用途,它可能是这样的

    def f(a, b, c): 
      print a, b, c
    
    stuff = ['f',2,3,4]
    
    f(*stuff[1:]) ### equivalent to f(2,3,4)
    

    【讨论】:

      猜你喜欢
      • 2012-05-07
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 2016-05-26
      • 2012-12-06
      • 2021-03-09
      • 2011-09-02
      • 2014-11-30
      相关资源
      最近更新 更多