import sys
#print sys.argv[1]
def IndexSearchString():
This function search a string in a file through index and gives the result.
#fieldindex = int(sys.argv[1])-1
stringsrch = sys.argv[2]
#size = len(sys.argv)
file_name = open("passwd", "r")
#print "No of Argu ", size
'''
if sys.argv[1] == Null:
print "Please enter argument"
'''
if sys.argv[1].isdigit():
fieldindex = int(sys.argv[1])-1
else:
print "Enter integer in 1st Argument"
sys.exit(1)
fieldindex = int(sys.argv[1])-1
stringsrch = sys.argv[2]
if len(sys.argv) > 3 :
print "Enter two arguments only"
sys.exit(1)
for store_file in file_name:
temp = store_file.split(":")
search = temp[fieldindex]
#print search
if stringsrch in search:
print store_file
IndexSearchString()
'''
My Question is:
I am taking two argument in the command line. Now I want to handle when only one argument is given and also when no argument is given.
Help me out
Error:
Command Window Input: python SearchString.py 1
Traceback (most recent call last):
File "SearchString.py", line 46, in <module>
IndexSearchString()
File "SearchString.py", line 36, in IndexSearchString
stringsrch = sys.argv[2]
IndexError: list index out of range
'''
问问题
6021 次
4 回答
0
这个
stringsrch = sys.argv[2]
应该是这个
stringsrch = sys.argv[1]
因为你没有其他地方使用
系统.argv[2]
于 2013-10-10T07:04:58.980 回答
0
在您看来:您应该在 sys.argv 中从 0 开始
于 2013-10-10T07:07:22.940 回答
0
检查这个问题,看看它是否可以帮助
python 和 sys.argv
在你的“def ...”之后添加这个
if len(sys.argv) < 3 :
print "Please enter two arguments"
sys.exit(1)
并改变你的另一个
if len(sys.argv) > 3 :
print "Enter two arguments only"
sys.exit(1)
至
if len(sys.argv) > 4 :
print "Enter only two arguments after the program"
sys.exit(1)
更容易
if len(sys.argv) >= 0 | len(sys.argv) < 3 :
fieldindex = int(sys.argv[1])-1
else:
sys.exit("enter up to 2 args")
于 2013-10-10T08:12:11.153 回答