Argument passing

Okay, starting to hit the tutorial for 2.7 over at python.org, and wanted to work out argument passing:

2.1.1. Argument Passing

When known to the interpreter, the script name and additional arguments thereafter are turned into a list of strings and assigned to the argvvariable in the sys module. You can access this list by executing import sys. The length of the list is at least one; when no script and no arguments are given, sys.argv[0] is an empty string. When the script name is given as '-' (meaning standard input), sys.argv[0] is set to '-'. When -c command is used, sys.argv[0] is set to '-c'. When -m module is used, sys.argv[0] is set to the full name of the located module. Options found after -c command or -m module are not consumed by the Python interpreter’s option processing but left in sys.argv for the command or module to handle.

Also – quick shout out to: how can i run my python program directly from the shell

Right.  What’s that all mean? Here’s my program, “test.py”:

#!/usr/bin/env python2.7
import sys
print "i am test.py and sys.argv[0] is: %s\n" \
      "and len(sys.argv) is: %d\n" \
      "and sys.argv is:" \
      %(sys.argv[0], len(sys.argv)), \
      sys.argv

Note, it’s executable:

PY$ ls -las test.py
8 -rwxr-xr-x 1 mgh wheel 129 Jan 19 22:52 test.py

And some results:

PY$ python test.py
i am test.py and sys.argv[0] is: test.py
and  len(sys.argv) is: 1
and sys.argv is: ['test.py']

PY$ # one arg
PY$ python test.py 1st
i am test.py and sys.argv[0] is: test.py
and len(sys.argv) is: 2
and sys.argv is: ['test.py', '1st']

PY$ # without python
PY$ ./test.py 1st 2nd
i am test.py and sys.argv[0] is: ./test.py
and len(sys.argv) is: 3
and sys.argv is: ['./test.py', '1st', '2nd']

PY$ ./test.py 1 2 'it works!'
i am test.py and sys.argv[0] is: ./test.py
and len(sys.argv) is: 4
and sys.argv is: ['./test.py', '1', '2', 'it works!']
PY$

OH SNAP — that’s cool. I just realized that “pythonic year” abbreviates to “PY”. Honestly, I did NOT plan THAT! Neato.

Okay, here’s a bit of an improvement using multi-line strings with triple-quote: ”’

test2py:

#!/usr/bin/env python2.7
import sys
print '''i am test.py 
     and sys.argv[0] is: %s
     and len(sys.argv) is: %d 
     and sys.argv is: %s
     '''%(sys.argv[0], len(sys.argv), sys.argv)

And results:

PY$ ./test2.py 
i am test.py 
     and sys.argv[0] is: ./test2.py
     and len(sys.argv) is: 1 
     and sys.argv is: ['./test2.py']

PY$ ./test2.py 1 2 3 'str w/space'
i am test.py 
     and sys.argv[0] is: ./test2.py
     and len(sys.argv) is: 5 
     and sys.argv is: ['./test2.py', '1', '2', '3', 'str w/space']

PY$

Leave a Reply