【问题标题】:Hoy can I pass "whole" cli arguments to a function in python我可以将“整个”cli参数传递给python中的函数吗
【发布时间】:2013-12-28 19:19:50
【问题描述】:

我被这个卡住了

我有一个从其他地方作为模块导入的 python 文件,以便使用它提供的一些功能。我正在尝试一种从 CLI 中调用它的方法,给它 0 或 5 个参数。

def simulate(index, sourcefile, temperature_file, save=0, outfile='fig.png'):
    (...)
    # do calculations and spit a nice graph file.

if __name__ == '__main__':

    if (len(sys.argv) == 6 ):
        # ugly code alert
        simulate(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
    else:
        (...)
        #do some other things and don't bother me

我想知道是否有一种干净的方法可以将除第一个参数之外的所有参数都传递给函数。 我尝试了simulate(sys.argv[1:]),但它抛出了一个对象(列表),并且由于模拟函数需要 4 个参数,它不起作用:TypeError: 'simulate() takes at least 3 arguments (1 given)' 也尝试了simulate(itertools.chain(sys.argv[1:])),结果相同。

由于这个文件作为一个模块被导入到其他地方并且这个函数被多次调用,改变函数的签名来接收单个参数似乎是个坏主意

【问题讨论】:

    标签: python command-line-arguments argument-passing


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      您要使用的在 Python 中称为“打包/解包”:

      foo(*sys.argv)
      

      见:http://en.wikibooks.org/wiki/Python_Programming/Tuples#Packing_and_Unpacking

      如果你想要“除了第一个参数之外的所有参数”:

      foo(*sys.argv[1:])
      

      这称为“切片”。见:http://docs.python.org/2.3/whatsnew/section-slices.html

      【讨论】:

        猜你喜欢
        • 2013-08-08
        • 1970-01-01
        • 1970-01-01
        • 2011-02-20
        • 1970-01-01
        • 2014-02-15
        • 2015-09-23
        • 2011-01-10
        • 2015-04-28
        相关资源
        最近更新 更多