Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass sys.argv[n] into a function in Python

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.

like image 281
Greg Avatar asked Jul 08 '13 09:07

Greg


People also ask

How do I pass SYS argv in Python?

How do I use SYS argv in Python script? To use, sys. argv in a Python script, we need to impo r t the sys module into the script. Like we import all modules, "import sys" does the job.

How does Sys argv work in Python?

sys. argv is the list of commandline arguments passed to the Python program. argv represents all the items that come along via the command line input, it's basically an array holding the command line arguments of our program. Don't forget that the counting starts at zero (0) not one (1).

How do you pass a command line argument to a function in Python?

In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys ( sys. argv ) will store all the information in the command line entry and can be accessed inside the Python script. Python's getopt module can also be used to parse named arguments.


1 Answers

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

like image 138
Harry.Chen Avatar answered Sep 28 '22 14:09

Harry.Chen