简体   繁体   English

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

[英]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: 键入以下命令时,请在控制台中尝试以下操作:$ python py.py xxx,显示xxx当我不带参数时将其显示为错误:

Traceback (most recent call last): File "py.py", line 4, in if sys.argv[1] : IndexError: list index out of range 追溯(最近一次调用):文件“ py.py”,第4行,如果sys.argv [1]:IndexError:列表索引超出范围

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. 您会看到我也将[1]更改为[1:],现在,如果我在控制台中键入“ $ python py.py”而忘记了不返回错误的参数。 Whats happen in the behind the scene? 幕后发生了什么?

sys.argv is a list of arguments. sys.argv是参数列表。 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 . 因此,当您在不带任何参数的情况下执行脚本时,您正在访问的索引1的列表为空,而访问空列表的索引将引发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. 使用第二个代码块,您正在做一个列表切片,并且正在检查索引1和向前的列表切片是否不为空,然后打印列表的该切片。 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). sys.argv是一个参数列表(您在终端中将其与命令一起传递),但是当您不传递任何参数并访问空列表的索引1时,则会出现明显的错误(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. 但是,在第二种情况下,您正在从索引1进行切片,并使用索引> 1的列表成员,即使该列表为空也应该没有问题,因为切片后的列表也将为空,而我们没有错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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