简体   繁体   中英

python sys.argv[1] vs. sys.argv[1:]

I wrote this code:

#!/usr/bin/env python
import sys

if sys.argv[1] :
    print sys.argv[1]

Try this in console when typed: $ python py.py xxx that prints xxx When i leave it with no parameter an error appears:

Traceback (most recent call last): File "py.py", line 4, in if sys.argv[1] : IndexError: list index out of range

Now with a few changes:

#!/usr/bin/env python
import sys

if sys.argv[1:] :
    print sys.argv[1:]

You see i changed [1] to [1:] as well and now if i type "$ python py.py " in console and forget the parameter that returns no error. Whats happen in the behind the scene?

sys.argv is a list of arguments. So when you execute your script without any arguments this list which you're accessing index 1 of is empty and accessing an index of an empty list will raise an IndexError .

With your second block of code you're doing a list slice and you're checking if the list slice from index 1 and forward is not empty then print your that slice of the list. Why this works is because if you have an empty list and doing a slice on it like this, the slice returns an empty list.

last_list = [1,2,3]
if last_list[1:]:
    print last_list[1:]
>> [2,3]

empty_list = []
print empty_list[:1]
>> []

sys.argv is a list of arguments (which you passed in along with your command in terminal) but when you are not passing any arguments and accessing the index 1 of the empty list it gives an obvious error (IndexError). but, in the second case where you are doing slicing from index 1 and using the members of the list with index >1 there should not be a problem even if the list is empty since then the sliced list will also be empty and we get no error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM