首页 > 解决方案 > 解释器跳过 sys.argv 中的部分代码

问题描述

我在 if 语句中有代码,它检查是否在命令行中传递了 argv,但是如果用户没有传递任何参数(只是文件名),我有一部分代码应该运行。解释器不运行该代码,而是立即跳转到如果用户键入 argv 应运行的代码并打印 IndexError: list index out of range。

import sys
if sys.argv[1] == '--list':
    do sth
elif sys.argv[1] == '--remove':
    do sth
else: (Which I thought will be ran with no arguments)
    this part of code is skipped no matter what

如果没有输入任何参数,如何让解释器在 else 语句中运行代码?

标签: python-3.x

解决方案


您正在尝试访问长度为 1 的数组的元素 1。

您应该做的是检查数组的长度,然后才尝试访问它。

import sys

if len(sys.argv) == 1:
    # do something when no arguments are given
    pass
else:
    if sys.argv[1] == 'hi':
        print("hi")

推荐阅读