【发布时间】:2013-06-11 21:01:13
【问题描述】:
为什么带有负索引的 sys.argv 应该允许打印与 sys.argv[0] 相同的值?同样,它也允许传递最多数量的参数。
因此,在developers.google.com 上调用hello.py,如下所示(带有3 个参数,包括脚本名称):python hello.py Sumit Test
将允许访问 sys.argv[-1]、[-2] 和 [-3],它们都打印与 argv[0] 相同的值,即 hello.py,但 argv[-4] 会抛出预期错误:
Traceback (most recent call last):
File "hello.py", line 35, in <module>
main()
File "hello.py", line 31, in main
print (sys.argv[-4])
IndexError: list index out of range
代码是:
import sys
# Define a main() function that prints a little greeting.
def main():
# Get the name from the command line, using 'World' as a fallback.
if len(sys.argv) >= 2:
name = sys.argv[1]
else:
name = 'World'
print ('Hello', name)
print (sys.argv[-3])
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
【问题讨论】:
-
我无法理解这部分“sys.argv[-1]、[-2] 和 [-3],它们都打印与 argv[0] 相同的值”。他怎么不能是“python hello.py Sumit Test”,它们应该是'Test''Sumit''hello.py'。
-
@olrg - 我编辑了问题以在其中插入代码。我指的是行 print (sys.argv[-3])。