Reputation: 257
I am trying to pass "sys.argv[1]" into a function.
#!/usr/bin/env/ python
import sys
def main():
test(sys.argv[1])
def test(sys.argv[1]):
print "Hello " + sys.argv[1]
./arg.py World
File "./arg.py", line 5
def test(sys.argv[1]):
^
SyntaxError: invalid syntax
Not sure where to go from here after scowering the Interwebs for a few hours. I have also tried to set the "sys.argv[1]" to a variable and tried passing that into the function and still no avail.
Upvotes: 5
Views: 34094
Reputation: 1610
I think you misunderstand the declaration and call of a function. In your program,there is only declaration,missing the calling statement. As for passing parameters from command line,here is an example which I prefer:
import sys
def hello(v):
print 'hello '+v
def main(args):
hello(args[1])
if __name__ == '__main__':
main(sys.argv)
The program start to execute from the line 'if name == 'main' by calling the function defined previously and passing the sys.argv as parameter
Upvotes: 11
Reputation: 59974
sys.argv[1]
returns a string, so you can't add that as a parameter/argument.
I don't see why you would need this, just put no arguments at all:
def test():
print "Hello " + sys.argv[1]
You may have also gotten mixed up. Argument names do not need to be the same name as what you would use when calling the function. For example, if I had n = 5
, the function does not need to have an argument called n
. It can be anything.
So you can do:
def test(myargument):
print "Hello " + myargument
I'm just going to give you a quick little "tutorial" on arguments.
def myfunc():
print "hello!"
Here we have a function. To call it, we do myfunc()
, yes? When we do myfunc(), it prints "hello!".
Here is another function:
def myfunc(word):
print word
This function takes an argument. So when we call it, we have to add an argument. Here's an example of calling the function:
def myfunc(word):
print word
myword = 'cabbage'
myfunc(myword)
Notice how 'cabbage'
is set in the myword
variable. It does not have to be the same as what we called the argument in the function. Infact, we don't even have to create a variable if we need. We can just do myfunc('cabbage')
.
Also, in this example, you can only input one argument, as when we def
ined the function, we only used one parameter. If you add two, you'll get something like myfunc takes one argument (two given)
.
We called the argument word
so we can use that in the function. Notice how I have print word
and not print myword
. It's as if we did word = myword
, but instead of doing that step, we use the argument name.
Upvotes: 6