【发布时间】: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