Fish OnTray
Fish OnTray

Reputation: 199

python sys.argv can't get the argument value?

I tried to pass some variables to my python code . the variable is a list, after i run the python script . which is simply just print out sys.argv. the output is following:

:~ xxx$ /var/folders/kg/qxxxxxd343433gq/T/Cleanup\ At\ Startup/pdTry-375321896.860.py.command ; exit;
var1, var2, var1, var2
the len argv is 1
/Users/xxx/python/pdTry.py
Traceback (most recent call last):
File "/Users/xxx/python/pdTry.py", line 58, in <module>
main()
File "/Users/xxx/python/pdTry.py", line 33, in main
print (sys.argv[1])
IndexError: list index out of range
logout

you can see the the list contains var1 and var2 actually print out 2 times. but i can get the value, the len sys.argv is 1. No value for sys.argv[1]. Do anyone know why? Why the length is 1, should it be 2? arg[0] is the script name, and arg[1] is the variable list i passed to it?

The code is simply

 def main():
   os.system ('osascript up.scpt')
   #print (sys.argv)
   a= 'the len is '+str(len(sys.argv))
   print (a)
   print (sys.argv[0])
   print (sys.argv[1])

Upvotes: 0

Views: 3824

Answers (3)

moon.musick
moon.musick

Reputation: 5664

It seems you left out any real arguments for the script, which could be added to the sys.argv list. In the call you posted, I see no list of variables passed to the script. If the semicolon separating the commands (the script name and exit shell builtin) was escaped, then most likely you would have len(sys.argv) equal to 3 (but I doubt it was your original intention to have the semicolon and exit as sys.argv values).

# simple test script
$ cat exittest.py
import sys
print(sys.argv, len(sys.argv))

# and some calls
$ python3.2 exittest.py
['exittest.py'] 1

$ python3.2 exittest.py \; exit
['exittest.py', ';', 'exit'] 3

# and for a similar call as you posted I ssh'ed to my localhost
# to test it with exit builtin
$ python3.2 exittest.py ; exit
['exittest.py'] 1

Upvotes: 0

aw4lly
aw4lly

Reputation: 2155

Remember that lists in python start at 0.

List Length   : 1 2 3 4
Element number: 0 1 2 3
Data          : A B C D  

so when you have length 1 you only have 1 element (argv[0]) which means argv[1] doesn't exist.

Upvotes: 2

Mayank
Mayank

Reputation: 357

Dude,

you are reading argv[[1] when your length is 1. How can array of length have two items ( read 0th and 1st item).

Upvotes: 0

Related Questions