python-3.x - 解释器跳过 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 语句中运行代码?
解决方案
您正在尝试访问长度为 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")
推荐阅读
- python-3.x - 如何在列表中查找重复项并附加到新列表
- python - 有没有办法使用 xlsxwriter 将熊猫数据框发送到现有的 excel 工作表?
- node.js - 如何在 NodeJS 中缓存来自谷歌驱动器 API 的响应
- java - java中 Rectangle.contains() 的错误结果
- c# - 如何使用 C# 中的引用从构造函数中分配对象
- javascript - 如何修复,可滚动内容的固定布局
- android - Android匹配父母留下了正确的差距
- html - 悬停时 div 下方的小蓝色“下划线” - 这是从哪里来的?
- java - 从python转置矩阵
- git - 尝试使用 SSH 身份验证从 Google Cloud Source Repositories 克隆 repo