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

查看:58
本文介绍了python sys.argv[1] 与 sys.argv[1:]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这段代码:

#!/usr/bin/env python
import sys

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

输入时在控制台中试试这个:$ python py.py xxx打印 xxx当我不带参数离开它时会出现错误:

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

回溯(最近一次调用最后一次):文件py.py",第 4 行,在if sys.argv[1] : IndexError: list index out of range

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

现在有一些变化:

#!/usr/bin/env python
import sys

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

你看到我也将 [1] 更改为 [1:],现在如果我在控制台中输入$ python py.py"并忘记不返回错误的参数.幕后发生了什么?

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 是一个参数列表.因此,当您在没有任何参数的情况下执行脚本时,您正在访问索引 1 的此列表为空,而访问空列表的索引将引发 IndexError.

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.

使用您的第二个代码块,您正在执行一个列表切片,并且您正在检查是否索引 1 和向前的列表切片不为空,然后打印您的列表切片.这样做的原因是因为如果您有一个空列表并像这样对其进行切片,则切片返回一个空列表.

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]
>> []

这篇关于python sys.argv[1] 与 sys.argv[1:]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆