【问题标题】:Python check if variable is set or empty [duplicate]Python检查变量是否设置或为空[重复]
【发布时间】:2018-03-21 16:24:39
【问题描述】:

我需要检查输入变量是否设置,我使用python 3.5,例如:

./update-stack.py stack-name(使用堆栈名称作为参数有效)

改为

./update-stack.py(没有堆栈名称我有错误)

Traceback (most recent call last):
  File "update-stack.py", line 22, in <module>
    stack = sys.argv[1]
IndexError: list index out of range

我写这个是为了检查这个:

if len(sys.argv) <= 0:
    print('ERROR: you must specify the stack name')
    sys.exit(1)

stack = sys.argv[1]

如何查看print 而不是错误?

谢谢

【问题讨论】:

  • try... except...
  • 使用if len(sys.argv) &lt;= 1:
  • 我建议首先尝试了解sys.argv 是什么。

标签: python python-3.x


【解决方案1】:

sys.argv至少一个元素,sys.argv[0] 是脚本或模块名称(或在命令行使用该开关时-c)。

你需要测试你是否有少于 2 个元素:

if len(sys.argv) <= 1:

或者您可以捕获IndexError 异常:

try:
    stack = sys.argv[1]
except IndexError:
    print('ERROR: you must specify the stack name')
    sys.exit(1)

附带说明:我会将错误消息打印到sys.stderr

print('ERROR: you must specify the stack name', file=sys.stderr)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 2012-10-31
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    相关资源
    最近更新 更多