开发者

Python: Assign multiple values at once: pass all argv arguments to a function

I want to pass all argv arguments to a function. I have created this code, but it gives me an error. How knows how to make this work? Many thanks for your help.

if __name__ == "__main__":
    import sys
    createP(sys.argv[1:])

def createP( a, b, c):
    print a + b + c

I am r开发者_如何学Gounning this app using the commandline:

python filename.py d e f

Returning:

NameError: name 'createP' is not defined


You're calling createP before you define it. You're also passing the wrong number of arguments to it; you need to expand the array:

def createP( a, b, c):
    print a + b + c

if __name__ == "__main__":
    import sys
    createP(*sys.argv[1:])


Try switching the order between the definition and the if.


You must inverse the order, as already said.
And to display variable lengths of argv, you should write:

def createP(*x):
    print '\n'.join(x)
    # or ' '.join(x) if you prefer

if __name__ == "__main__":
    import sys
    createP(*sys.argv[1:])

I suppose that all elements of sys.argv are strings. Am I right ?

Update

Well, my answer is a bit stupid; why the following code (without * for passing arguments and for definition of parameters) wouldn't be convenient ? :

def createP(x):
    print '\n'.join(x)
    # or ' '.join(x) if you prefer

if __name__ == "__main__":
    import sys
    createP(sys.argv[1:])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜