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.
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With