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
'''
答案 0 :(得分:0)
此
stringsrch = sys.argv [2]
应该是这个
stringsrch = sys.argv [1]
因为你没有其他地方使用
sys.argv中[2]
答案 1 :(得分:0)
:你应该在sys.argv
中以0开头答案 2 :(得分:0)
检查这个问题,看看它是否有用
python and 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")
答案 3 :(得分:0)