[英]How to know if third argument is passed to script?
I am working on a script that uses English words for their argument, not the traditional --argument
or -a
. 我正在编写一个使用英文单词作为其参数的脚本,而不是传统的
--argument
或-a
。
I have not dare to deal this with argparse, but when I do this with sys.argv like this: 我不敢用argparse来处理这个问题,但是当我用sys.argv这样来做这件事时:
if sys.argv[3]:
print('yes, there is a third argument')
I get an IndexError: list index out of range
. 我收到
IndexError: list index out of range
。 What is the possible way to tackle this? 解决这个问题的可能方法是什么? I want to know if there is third argument.
我想知道是否有第三个论点。
You want to check the length of argv
: 您要检查
argv
的长度:
if len(sys.argv) > 3:
print('yes, there is a third argument')
If you have time, though, it's worth learning argparse. 但是,如果您有时间,值得学习argparse。 It's not too scary, and it makes your code much easier to read.
它不是太吓人,它使您的代码更易于阅读。
You can use len()
to check the length first or catch the IndexError
. 您可以使用
len()
首先检查长度或捕获IndexError
。
if len(sys.argv) > 3:
# all three arguments are present
print 'arg1', sys.argv[1], 'arg2', sys.argv[2], 'arg3', sys.argv[3]
or: 要么:
try:
arg1, arg2, arg3 = sys.argv[1], sys.argv[2], sys.argv[3]
except IndexError:
# arguments are missing
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.